Bootstrapper
Bootstrapper

Reputation: 1159

backbone model - howto execute outer functions from event handlers?

In Backbonejs, is it possible to initialize event handlers in a loop even when the handlers make use of the functions in the outer model?

For e.g. how can I get something like the below to work?

var MyModel = Backbone.Model.extend({
    eventHandlers: {
        onerror: function(e) {
            this.myErrorHandler(e); // doesnt work
        },
    },

    initialize: function () {
        var myObj = {}
        _.each(eventHandlers, function(value, key) {
            myObj[key] = value;
        }, this);
    },

    myErrorHandler: function(e) {
        console.error('my error handler', e);
    }
});

How do I get the Model's error handler function (myErrorHandler) to be called from the event handlers that are declared in a sub object? Or is there some other way to achieve this?

TIA

Upvotes: 0

Views: 76

Answers (1)

Artur Nowak
Artur Nowak

Reputation: 5354

Do you mean to execute each handler on event defined by its key, bound to the model instance?

var MyModel = Backbone.Model.extend({
    eventHandlers: {
        error: function(e) {
            this.myErrorHandler(e); // doesnt work
        }
    },

    initialize: function () {
        var _this = this;
        _.each(this.eventHandlers, function(value, key) {
            _this.on(key, _(value).bind(_this));
        });
    },

    myErrorHandler: function(e) {
        console.error('my error handler', e);
    }
});

But what if you want to have several handlers for the same event?

Upvotes: 1

Related Questions