Search code examples
javascriptbackbone.js

Backbone events between view and controller


I'm trying to use Backbone events in a Model-View-Controller pattern. My controller is just a JavaScript class, so I've extended it like this to support Backbone events:

function Controller() {
    _.extend(this, Backbone.Events);

    this.listenTo(view, 'some:event', this.onSomeEvent);

    this.onSomeEvent = function() {
        // ... This code never executes.
    }
}

My view is a Backbone view that does this when a button is clicked:

onClick: function() {
    this.trigger('some:event');
}

The onClick() method executes in response to the button click, but the onSomeEvent() method of the controller never executes. What am I doing wrong?


Solution

  • this.onSomeEvent should be defined before the call this.listenTo. Right now this.onSomeEvent is undefined when assigned as a listener.

    You could also define your controller like this

    function Controller() {
        _.extend(this, Backbone.Events);
    
        this.listenTo(view, 'some:event', this.onSomeEvent);
    }
    
    Controller.prototype.onSomeEvent = function() {
        // code
    };
    

    and call the controller like this new Controller()