ped*_*ete 4 collections backbone.js
我有什么应该很简单.我创建了一个新的集合,我想将它传递给渲染并将集合模型添加到页面中.
get_results: function(){ $.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) },
这会返回错误
Uncaught TypeError: undefined is not a function
我的收藏品有一个普通的结构
_byCid: Object _byId: Object _onModelEvent: function () { [native code] } _removeReference: function () { [native code] } length: 7 models: Array[7] __proto__: o
我已经尝试了很多东西,但是有一件事情可能是我必须通过,
this.search_results.models.each(this.render_match);
因为那是实际的阵列,但如果我这样做,我会得到一个Uncaught typeError: Object [object Object],[object Object],...
当调用每个方法的回调函数时,您将丢失执行上下文
_.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)
},
Run Code Online (Sandbox Code Playgroud)
虽然从我所看到的 - 我假设你在这里展示的代码是模型或集合 - 处理呈现视图 - 你不应该这样做!模型和集合仅用于存储和解析数据 - 所有呈现和控制应用程序流都应在路由器的帮助下在View(控制器)中完成.