0

I'm using Backbone, but I feel this is more of a general javascript syntax question.
How can I add a method inside a method (or a function inside a function) and call them by chaining both?

var myModel = Backbone.Model.extend({

    method1: function(x){
        method2: function(y){
            return x*y;
        }
    }

    // or perhaps
    method1: function(x){
        {
            method2: function(y){
                x = x*y;
            }
        }
        return x;
    }
});

var mymodel = new myModel();
mymodel.method1(3).method2(5); // outputs 15

1 Answer 1

1

Usually the chaining is acheived by returning the original object.

var myModel = Backbone.Model.extend({
    methodSub: function(x){
        this.x -= x;
        return this;
    },
    methodAdd: function(y){
        this.y += y;
        return this;
    }
});

Or like this: (but then it's essentially another object and should be defined appropriately)

var myModel = Backbone.Model.extend({
    methodSub: function(x){
        this.x -= x;
        return {
             x : this.x,
/*           val : this.x, Or simply val, if that seems appropriate */
             methodAdd: function(y){
                this.x += y;
                return this;
             }
        }
    }
});

Don't know if any of them is the way you imagined. But in essence, you have to return something to chain something. Else the method will return undefined and you can't call a method "on" undefined.

Sign up to request clarification or add additional context in comments.

5 Comments

Not really. When I call method1 alone, it cannot return this. I need method1 to know wether method2 is chained after it.
Dont think you can "know" if a method is chained after or not. But you could so something like (ill change the answer)
That works great! But how can I return x when just calling mymodel.methodSub(3)?
Dont know if theres a better way but you can add x : x in the map I guess. Ill update
I'm not having any success with that :/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.