This article mainly introduces the JavaScriptDSL fluent interface (called using a chain) instance. This article describes the DSL fluent interface, DSL expression generator, and other content. if you need it, you can take a closer look at DSL, one of the most interesting things found in JavaScript is chained call (Method Chaining ). Interestingly, Martin Flower points out:
The code is as follows:
I 've also noticed a common misconception-please people seem to equate fluent interfaces with Method Chaining. certainly chaining is a common technique to use with fluent interfaces, but true fluency is much more than that.
Many people equate chained calls with smooth interfaces. However, chained invocation is a common method for smooth interfaces. actually smooth interfaces are more than that.
DSL smooth interface
The original intention of a smooth interface is to build a readable API. after all, the code is written to people.
Similarly, let's take a look at how we operated DOM through method cascade.
The code is as follows:
Var btn = document. createElement ("BUTTON"); // CreateElement
Var t = document. createTextNode ("click me"); // Create a text node
Btn. appendChild (t); // Append the text
Document. body. appendChild (btn); // AppendTo
This is what I wrote with jQuery.
The code is as follows:
$ (''). Append (" click me ");
And so on.
Then we can create a simple example to show the simplest DSL.
The code is as follows:
Func = (function (){
This. add = function (){
Console. log ('1 ');
Return this;
};
This. result = function (){
Console. log ('2 ');
Return this;
};
Return this;
});
Var func = new Func ();
Func. add (). result ();
However, this looks like an expression generator.
DSL expression generator
The expression generator object provides a set of coherent interfaces, which are then converted to calling the underlying command-Query API.
For such APIs, we can see in some APIs about databases:
The code is as follows:
Var query =
SQL ('select name, desc from widgets ')
. WHERE ('price <', $ (params. max_price), AND,
'Clearance = ', $ (params. clearance ))
. ORDERBY ('name asc ');
One problem with chained calling is that we have not finished the code above, which is confusing .. Adding a query and end seems to be a good result.
Others
Method cascade
The statement is as follows:
The code is as follows:
A. B ();
A. c ();