【问题标题】:backbone.js collection not responding to .each骨干.js 集合没有响应 .each
【发布时间】:2012-01-14 21:06:14
【问题描述】:

我有什么应该很简单的。我创建了一个新集合,我想将它传递给渲染并将集合模型添加到页面。

获取结果:函数(){ $.getJson(this.url,function(response){ this.search_results = new Kitchon.Collections.searchList(response); console.log(this.search_results); this.search_results.each(this.render_match); } }, 渲染匹配:函数(模型){ 控制台日志(模型) },

这会返回一个错误

Uncaught TypeError: undefined is not a function

我的收藏有一个普通的结构

_byCid:对象 _byId:对象 _onModelEvent: function () { [本机代码] } _removeReference: function () { [本机代码] } 长度:7 型号:数组[7] __proto__:o

我尝试了很多东西,但最突出的一件事是我可能不得不通过 this.search_results.models.each(this.render_match); 因为那是实际的数组,但如果我这样做,我会得到一个 Uncaught typeError: Object [object Object],[object Object],...

【问题讨论】:

    标签: collections backbone.js


    【解决方案1】:

    当每个方法的回调函数被调用时,你会丢失执行上下文

    在传递回调时使用_.bind(this.render_match, this) 以确保render_match 具有正确的上下文

    你得到了错误,因为你也没有为getJson 方法包装回调函数。您还必须在此处使用下划线bind 方法。

    您应该阅读一些关于 javascript this 以及如何驯服它的信息 - 在这里试试 http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/

    正确的代码应该或多或少像这样......

    get_results: function(){
    
        $.getJSON(this.url, _.bind(function(response){
    
            this.search_results = new Kitchon.Collections.searchList(response);
            console.log(this.search_results);
            this.search_results.each(_.bind(this.render_match, this));
        }, this));
    },
    render_match: function(model){
    
        console.log(model)
    },
    

    尽管从我所见 - 我假设您在此处显示的代码是模型或集合 - 正在处理呈现视图 - 您不应该这样做!模型和集合仅用于存储和解析数据 - 所有渲染和控制应用程序流程都应在路由器的帮助下在视图(控制器)中完成。

    【讨论】:

    • 谢谢汤姆,我知道它在某种程度上迷失了“这个”,但我不知道如何让它工作。 Yehuda 的文章是一个很好的补充。很难搜索“this”并返回相关结果。
    【解决方案2】:

    $.getJson 更改 this 引用。 jquery 中的很多方法都是这样做的,所以this.render_match 的值为空。您将 null 传递给 each 并失败。

    要解决这个问题,请在$.getJson 之前创建一个对此的引用(如var _this = this;),并使用它来代替this。代码应如下所示:

    get_results: function(){
        var _this = this;
        $.getJson(this.url,function(response){
            _this.search_results = new Kitchon.Collections.searchList(response);
            console.log(_this.search_results);
            _this.search_results.each(_this.render_match);
        }
    },
    render_match: function(model){
        console.log(model)
    },
    

    【讨论】:

    • 您在每个循环中再次丢失了 this 上下文 - 检查我的答案
    【解决方案3】:

    只是在这里尝试一下(我对 Backbone.js 一无所知),但这不是您要寻找的:

    $.each(this.search_results, function(index, value) { 
      alert(index + ': ' + value); 
    });
    

    祝你好运!

    【讨论】:

    • Backbone.js 将许多 underscore.js 方法映射到集合 - 当你手头有 underscorejs 时,你不需要也不应该使用 jquery - 它的实现有点更快 + this.search_results 不是真正的 Array 而是 Backbone.Collection 实例 - 如果您想直接迭代模型,则需要访问集合上的 models 属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多