简体   繁体   中英

javascript - how to "fluent API" (also calling "chaining")?

I am trying to understand is how to create call methods after a method call.

For example in jquery you have something like this:

$("blah").data("data-id");

How would I make :

blah("cow").foo("moo");

Where the mothods blah and foo just console.log(value) ?

What you're referring to is a "fluent API" (also calling "chaining"). Your functions need to return the object that has the next method you want to call on it. For example,

 var obj = function(){ var self = this; self.blah = function(v){ console.log(v); return self; }; self.foo = function(v){ console.log(v); return self; }; }; var o = new obj(); o.blah("cow").foo("moo");

See this article for more info: http://www.i-programmer.info/programming/javascript/4676-chaining-fluent-interfaces-in-javascript.html

Return the object that contains the functions when the function is done. then you can chain them.

Here is an example from what I made a while back:

// I extend a class with a new function
HtmlObject.prototype.stop = function () {

    clearInterval( this.updater );
    this.animationQue   = [];
    this.updater        = undefined;

    // Then return the object that initially called the function
    return this;
};

So I could use it like object.stop().nextfuntion();

Also, In JQuery the $ is simply a shortcut to a JavaScript function.

I did the same in my test, but then with _ . I must admit it is not as nifty as JQuery but:

var _ = function ( selector, context ) {
    var el = new xyvLib();
    // This will simply return a collection of HtmlObjects (of which you can find a snipet above)
    return el.fn.select( selector, context );
};

The function blah has to return an object with a method foo. Here is an example:

function blah(blahArg) {
    return {
       foo: function (fooArg) {
            console.log(blahArg, fooArg);
       }
    };
}

blah("cow").foo("moo");

You can call .foo on the result of blah() only when blah() returns an object which accepts the method foo on it.

A simple example would be like this:

function foo(value) {
    console.log(value);
}
function blah(value) {
    console.log(value);
    return { foo: foo } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM