Search code examples
javascriptbackbone.jsbackbone-viewsbackbone-routing

How can I set context of the error handler of Backbone model fetch?


I'm using a Router to organise my Backbone app. In my edit route I'm calling fetch on a model instance to get the model's data for the edit form:

App.Router = Backbone.Router.extend({

    routes: {
        "": "index",
        "edit(/:id)": "edit"
    },

    index: function () {
        _.bindAll(this, "getItemByID", "onModelFetchError", "showError");
    },

    edit: function (id) {
        this.formEditItem = new App.Views.FormEditItem({model: this.getItemByID(id), parent: this});
    },

    getItemByID: function(id) {
        var item = new App.Models.Item({id: id});
        item.fetch({
            success: function(model, response, options) {
                console.log('Success');
                return model;
            },
            error: this.onModelFetchError
        })
    },

    onModelFetchError: function (model, response, options) {
        this.showError(response.responseText);
    },

    showError: function(msg) {
        this.error = new App.Views.Error({parent: this, message: msg});
    }

});

The fetch call works fine, but I'm having trouble handling errors. I want to instantiate an Error view and display the message in it. But when I try this code, I get "Uncaught TypeError: Object [object global] has no method 'showError'". It seems that assigning onModelFetchError as the handler for fetch errors puts it in the global scope, even when I bind it to the Router with _.bindAll.

Is there any simple way to ensure onModelFetchError remains in the Router scope?


Solution

  • You are calling to _.bindAll() inside of the index function which is fired by the route "", so if you don't fire that route they'll never get bind to the context object. I would suggest to create an initialize method for your router so you can bind all the functions for any route inside of it.

    initialize: function() {
        _.bindAll(this, "getItemByID", "onModelFetchError", "showError");
    }