3

我有以下情况:

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");
           }
         });
    }
});

当我运行它时,我收到以下错误

this.trigger不是函数

在外部方法上,我可以触发一些东西..比如

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

我做错了什么?或不做:)

4

3 回答 3

12

this在匿名函数中指的是ajax对象。这是因为 javascript 中的“this”会根据函数的范围发生变化。为了引用初始函数的“this”,请将其分配给不同的变量。以下将起作用:

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

编辑:查看如何确定“this”的解释

于 2012-04-05T14:07:45.630 回答
7

我个人更喜欢在模型上有一个saveSuccess方法。

    save: function() {
        var self = this;
        $.ajax({
            type    : "POST",
            url     : "/api/savetask",
            data    : this.toJSON(),
            success : this.saveSuccess
        });
    },
    saveSuccess: function(response) {
        this.trigger("something", "payload");
    }
于 2012-04-06T21:39:36.910 回答
0

This is a very late answer, but in case anyone else happens upon this page: there is a much better way. Using the self object (in my experience) is considered a bit of an anti-pattern, since we use underscore.js and have access to the bind function. Anyway, here's a better way:

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

It may be the case that the context attribute was added in a recent version of jQuery, and it wasn't available before. But this is (in my opinion) the best way to do it.

于 2015-06-18T20:21:10.530 回答