Michael Wilson
Michael Wilson

Reputation: 1579

making a function in an object chainable

I am trying to achieve a chainable object, but cannot figure out how I can do this within a function.

This is how I would like it to work:

$donate.ga('testing').go(value);

My object currently looks like this:

var $donate = {
    ga: function (value) {

    }
};

Upvotes: 1

Views: 78

Answers (4)

Utkarsh Vishnoi
Utkarsh Vishnoi

Reputation: 149

you have to return this; in each sub function before closing it. for example Your code

var $donate = {
    ga: function (value) {
       //perform your code here
       return this;  // <--- Dont forget to use this before closing the function nest
    },
    go: function(val) {
       //perform your code here
       return this;  // <--- Dont forget to use this before closing the function nest
    }
};

Upvotes: 0

B. Kemmer
B. Kemmer

Reputation: 1537

You need to return the Object like that:

var $donate = {
    ga: function (value) {
       //after some computation
       return this;
    },
    go: function(val) {
       //after some computation
       return this;
    }
};

If you don't return this (this is a reference to the current Object), you either return undefined or something else and your method defined in your Object is simply out of scope (unknown).

Upvotes: 0

Eenoku
Eenoku

Reputation: 2977

It's already solved here. You must simply return the object in your function.

Upvotes: 0

Konstantin Dinev
Konstantin Dinev

Reputation: 34905

You simply need to make each function to return the instance of the object:

var $donate = {
    ga: function (value) {
        // logic
        return this;
    }
};

Upvotes: 4

Related Questions