Example of JavaScript DSL fluent interface (called using a chain), dsl chain
After carefully studying DSL for a while, I found that one of the most interesting things in JavaScript is probably chained call (Method chain, that is, Method Chaining ). Interestingly, Martin Flower points out:
Copy codeThe 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.
Copy codeThe Code is as follows:
Var btn = document. createElement ("BUTTON"); // Create a <button> element
Var t = document. createTextNode ("click me"); // Create a text node
Btn. appendChild (t); // Append the text to <button>
Document. body. appendChild (btn); // Append <button> to <body>
This is what I wrote with jQuery.
Copy codeThe Code is as follows:
$ ('<Span>'). append ("click me ");
And so on.
Then we can create a simple example to show the simplest DSL.
Copy codeThe 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:
Copy codeThe 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:
Copy codeThe Code is as follows:
A. B ();
A. c ();