javascript - 在方法链中传递 'this' 上下文(使用应用/调用或绑定(bind))

标签 javascript backbone.js this

我试图在这个链接中传递 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/

相关文章:

c++ - 直接调用析构函数后 `new (this) MyClass();`是不是未定义行为?

c++ - 从转储中获取调用堆栈的几乎所有帧中的 this 指针 NULL 意味着什么?

javascript - 无法使用 .bind 更改分配给该对象的值

javascript - 动态异步 Mocha 测试

javascript - 轨道 3.1 和 Jasmine : Including JavaScripts from gems

javascript - 创建一个表单并编辑该表单但不保存(以 Angular 形式)?

backbone.js - Backbone 路由器或 View 是否应该处理获取数据并显示加载状态?

javascript - 主干模型未在 SAVE 上发送数据

javascript - 隐藏 Razor 引擎中的单选按钮

javascript - 如何用 JavaScript 写出 "array of pattern"?