var PlaylistView = Backbone.View.extend({
el: '#expanded-container',
initialize: function() {
this.bg = chrome.extension.getBackgroundPage();
this.$('.list-group').empty();
var realThis = this;
_.each(this.bg.Playlist.models, function (song) {
// append to playlist, rendering song template?
var songView = new SongView({ model: song });
console.log(realThis); // THIS is what I want
console.log(this) // this is NOT what I want
//this.$el.append(songView.render().el); // hence, this does NOT work
realThis.$el.append(songView.render().el); // and THIS works
});
}
});
在上面的代码中,_.each()
函数中的this
指向全局window
对象,因为_.each ()
由窗口调用。但是,我仍然希望 this
指向 PlaylistView
。我遇到过很多类似的情况,我经常定义一个变量来存储 this 的初始值,就像提供的示例中的 realThis
变量一样。还有其他常规方法可以解决这个问题吗?
注意:我正在关注 this学习Backbone的书,它显示了以下代码作为示例。
var ListView = Backbone.View.extend({
render: function(){
// Assume our model exposes the items we will
// display in our list
var items = this.model.get('items');
// Loop through each of our items using the Underscore
// _.each iterator
_.each(items, function(item){
// Create a new instance of the ItemView, passing
// it a specific model item
var itemView = new ItemView({ model: item });
// The itemView's DOM element is appended after it
// has been rendered. Here, the 'return this' is helpful
// as the itemView renders its model. Later, we ask for
// its output ("el")
this.$el.append( itemView.render().el ); // <--- *THIS IS WRONG?
}, this);
}
});
在这种情况下,_.each
循环中的 this
是否会指向错误的对象,就像在我的代码中一样?这是书上的错误还是我误解了什么?谢谢!
最佳答案
来自http://underscorejs.org/#each :
each
_.each(list, iterator, [context])
The iterator is bound to the context object, if one is passed.
在initialize()
中,this
指向您的Backbone View。如果您将 this
作为第三个参数传递给 _.each()
,那么 this
将在迭代器函数中引用您的 Backbone View。
I have faced many similar situations and I often defined a variable that stored the initial value of this, just like realThis variable in the provided example. Is there any other conventional way to deal with this?
是的。如果您处于 ES5(非 IE8)环境中,请使用 Function.prototype.bind()
。为了向后兼容,请使用 _.bind()
.
var func = function (greeting) {
return greeting + ': ' + this.name;
};
if (usingUnderscore) {
func = _.bind(func, {name: 'moe'}, 'hi');
} else if (es5environmentHooray) {
func = func.bind({name: 'moe'}, 'hi');
}
func();
=> 'hi: moe'
关于JavaScript 'this' 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23123069/