更改 "this" 范围 backbone collection.create

Change "this" scope for backbone collection.create

我用一种肮脏的方式来做这个,想知道是否有更好的方法:

this.collection.create(
    {
        'name': this.$('.name').val()
    },
    {
        success: function() {
            alert(_this);
        },
        error: function() {
            alert(_this);
        },
        wait: true
    }
);

我假设您已经在某处设置了 var _this = this;,但只是忘了包含它。

您可以做的是使用 Function.prototype.bind (EcmaScript 5) 将成功和错误回调绑定到正确的上下文。

success: function() {
    alert(this);
}.bind(this),

error: function() {
    alert(this);
}.bind(this),

IE9 及更高版本支持该功能。

(如果出于某种原因您支持 IE8,则 MDN 页面上有一个 polyfill)

使用最新的 backbonejs,您可以使用 context 关键字通过选项传递上下文,并且根本不使用任何 polyfills :

this.collection.create(
    {
        'name': this.$('.name').val()
    },
    {
        success: function() {
            alert(this);
        },
        error: function() {
            alert(this);
        },
        context: this,
        wait: true
    }
);