改变“this"主干集合的作用域

Change "this" scope for backbone collection.create

本文关键字:集合 作用域 this quot 改变      更新时间:2023-09-26

我用一种不太干净的方式来做这件事,想知道是否有更好的方法:

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页面上有一个填充)

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

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