Question

I have a backbone-extend.js file that I load in the require define in app.js. It has a Backbone.View extender class defining a couple helper methods. Two of the methods work just fine in my views, one always errors with Uncaught TypeError: Object [object global] has no method 'gotoUrl'. Why would just this one method be not defined but the other two are working fine? Do you see any issue in this code...

// Filename: backbone-extend.js

define([
    'jquery',
    'underscore',
    'backbone'
], function($, _, Backbone) {

    var helpers = {
        eventSyncError: function(model,response,options) {
            console.log('Sync error='+response.statusText);
            $('#server-message').css({'color':'red', 'font-weight':'bold'}).text(response.statusText);
        },

        gotoUrl: function(url,delay) {
            var to = setTimeout(function() { Backbone.history.navigate(url, true); }, delay);
        },

        getFormData: function(form) { 
            var unindexed_array = form.serializeArray();
            var indexed_array = {};

            $.map(unindexed_array, function(n, i) {
                indexed_array[n['name']] = n['value'];
            });

            return indexed_array;
        }
    }

    _.extend(Backbone.View.prototype, helpers);

});

Here is the code in view that calls it...

    eventSyncMemberSaved: function(model,response,options) {
        console.log("Member saved!");
        $('#server-message').css({'color':'green', 'font-weight':'bold'}).text("Member saved!");
        this.gotoUrl('members',2000);
        //setTimeout(function() { Backbone.history.navigate('members', true); }, 2000);
    },

    saveMember: function() {
        var data = this.getFormData($('#member-form'));
        this.member.save(data, { success: this.eventSyncMemberSaved });
    },

Thanks in advance for your help. I'm stuck.

Was it helpful?

Solution

The context of this is different in the success callback.

It no longer points to the view as it points to the xhr object

So it throws an error as that method is not available on the xhr object

To resolve it you need to bind the context of this to the success handler so that it points to the right object.

So in the initialize of the view add this code

initialize: function() {

    _.bindAll(this, 'eventSyncMemberSaved');
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top