JavaScript DSL fluent interface of USES chained call instances

  • 2020-05-16 06:19:30
  • OfStack

When I studied DSL carefully, I found a few interesting things. The most used thing for JavaScript is probably the chain call (method chain, Method Chaining). Interestingly, Martin Flower points out:


 I've also noticed a common misconception - many 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 fluent interfaces. However, chain-calling is a common method of fluent interfaces, and real fluent interfaces are more than just a little bit.

DSL smooth interface

The goal of the fluent interface was to build a readable API, after all, the code was written for people to see.

Similarly, let's take a quick look at 1. Earlier we used a method cascade to manipulate DOM


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>

If you write it in jQuery, it looks like this

$('<span>').append("CLICK ME");

, etc.

We can then create a simple example to show the simplest DSL


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();

This, however, looks like an expression generator.

DSL expression generator

The expression generator object provides a set of coherent interfaces, which are then converted into calls to the underlying command-query API.

This API, we can see in 1 API about database:


var query =
  SQL('select name, desc from widgets')
   .WHERE('price < ', $(params.max_price), AND,
          'clearance = ', $(params.clearance))
   .ORDERBY('name asc');

One e problem with chaining calls is the ending, which is confusing because we don't have an ending in the same code as above. Plus 1 query and 1 end seems like a good result.

other

Methods the cascading
As follows:


a.b();
a.c();


Related articles: