Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 601
K3NN3TH Avatar asked Aug 23 '26 20:08

K3NN3TH


1 Answers

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

like image 124
adam0101 Avatar answered Aug 26 '26 10:08

adam0101