Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I chain my method calls?

I have an object:

var mubsisapi = {
        step1   : function(){alert("a")}, 
        step2   : function(){alert("b")}
    }

$.extend(false, mubsisapi)
mubsisapi.step1().step2();

It is give step1() but not give step2(). step2() does not give an alert. How can I do this?

like image 358
Gürkan Pala Avatar asked Sep 27 '11 14:09

Gürkan Pala


4 Answers

Not JSON, but javascript object. It's not fluent, but it can be:

var mubsisapi = {
        step1   : function(){alert("a"); return this;}, 
        step2   : function(){alert("b"); return this;}
    }

$.extend(false, mubsisapi)
mubsisapi.step1().step2();
like image 175
Joe Avatar answered Sep 20 '22 12:09

Joe


You need to return this from the function if you want to chain it.

like image 31
Quentin Avatar answered Sep 22 '22 12:09

Quentin


Yes, your object should look like this:

var mubsisapi = {
    step1   : function(){alert("a"); return this; }, 
    step2   : function(){alert("b"); return this; }
}

returning itself to allow chaining.

like image 40
georgiar Avatar answered Sep 19 '22 12:09

georgiar


var mubsisapi = {
        step1   : function(){alert("a"); return mubsisapi;}, 
        step2   : function(){alert("b"); return mubsisapi;}
    }
like image 21
Mert Kabadayı Avatar answered Sep 20 '22 12:09

Mert Kabadayı