Search code examples
javascriptbackbone.jsunderscore.js

How can a backbone model trigger an event from an Ajax Result?


I have the following situation:

var Task = Backbone.Model.extend({
    initialize: function() {
    },
    save: function() {
        $.ajax({
           type    : "POST",
           url     : "/api/savetask",
           data    : this.toJSON(),
           success : function (response) {
           this.trigger("something", "payload");
           }
         });
    }
});

When I run this, I get the following error

this.trigger is not a function

On the external approach, I can trigger stuff.. like

var task = new Task();
task.trigger("something","payload");

What I am doing wrong? or not doing :)


Solution

  • this in the anonymous function refers to the ajax object. This is because "this" in javascript changes with respect to the scope of the function. In order to reference "this" of the initial function, assign it to a different variable. The following will work:

    save: function() {
        var self = this;
        $.ajax({
            type    : "POST",
            url     : "/api/savetask",
            data    : this.toJSON(),
            success : function (response) {
                self.trigger("something", "payload");
            }
        });
    }
    

    EDIT: See an explanation of how "this" is determined.