我正在尝试在此链接中传递this
上下文而没有任何'黑客' - 我只想使用apply,call或bind(描述如下):
var ArticlesCollection = Backbone.Collection.extend({
model: ArticleModel,
parse : function(response) {
var dateSinceFormatter = this.dateSinceFormatter; // right now solution
return _.chain(response)
.map(function(response) {
if(!_.difference(["id", "title", "link", "source", "image"], _.keys(response)).length) {
return {
id : (!response.id ? _.uniqueId() : response.id),
title : response.title,
content : response.preamble,
thumbnailUrl : ((!response.image) ? '' : response.image.url),
linkUrl: response.link,
timeAgo : '',
categoryName: '',
persistentUrl: response.link,
commentsEnabled: false
};
} else {
return {
id : response.id,
title : response.title,
content : response.preamble,
thumbnailUrl : response.thumbnail.url,
linkUrl: response.url,
timeAgo : dateSinceFormatter(response.published.datetime, response.published.niceformat), // I want to use this.dateSinceFormatter
categoryName: response.mainCategory,
persistentUrl: response.persistentUrl,
commentsEnabled: response.hasComments
};
}
})
.value();
}
});
任何想法?
答案 0 :(得分:2)
在显而易见的.bind()
解决方案旁边,Underscore's map
(就像native one)确实为回调的this
context提供了第三个参数:
response.map(function(res) { … }, this)
// or
_.map(response, function(res) { … }, this)
答案 1 :(得分:1)
您可以将上下文作为参数传递给大多数Underscore函数。例如,您可以调用
_.chain(response)
.map(function(response) {...}, this)
.value()