我试图在这个链接中传递 this
上下文,没有任何“黑客”——我只想使用应用、调用或绑定(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();
}
});
有什么想法吗?
最佳答案
在明显的 .bind()
旁边解决方案,Underscore's map
(就像 native one )确实为 this
context 提供了第三个参数回调:
response.map(function(res) { … }, this)
// or
_.map(response, function(res) { … }, this)
关于javascript - 在方法链中传递 'this' 上下文(使用应用/调用或绑定(bind)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21749685/