0

I am trying to create a simple callback system that would fire upon hitting a button. Rather than the callback being a factory function, it is a prototype method of a different object. I've gotten it to work but I don't understand it. Why do I need to use .bind(object) to get the object to fire its method? Originally I tried no bind, and then bind(this), which both failed.

function Bar() {}

Bar.prototype = {
    getStuff: function () {
        return "Hello";
    },

    setStuff: function () {
        console.log( this.getStuff() );
    }
}

function Foo() {
    this.afterSubmit = null;
    var self = this;
    $('button').click(function () {
        self.submit()
    });
    return this;
}

Foo.prototype = {
    submit: function () {
        if (this.afterSubmit !== null) {
            this.afterSubmit();
        }
        $('#msg').append('clicked ');
        return this;
    },

    setAfterSubmit: function (callback) {
        this.afterSubmit = callback;
        return this;
    }
}

var bar = new Bar();
var foo = new Foo().setAfterSubmit(bar.setStuff.bind(bar));
// Why do I need to bind bar ?

Please take a look at my fiddle https://jsfiddle.net/j5qfuzna/

1
  • 1
    When a method is fired, it is fired within the context of it's invoker unless implicitly declared otherwise ( .call, .apply, .bind ). Commented Jun 8, 2015 at 14:45

1 Answer 1

1
this.afterSubmit();

This is setting the context to the Foo instance. Binding it to the Bar instance prevents that from happening.

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

Comments

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.