我以一种肮脏的方式进行此操作,想知道是否有更好的方法:
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)