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) }, 获取_结果:函数(){ $.getJson(this.url,函数(响应){ this.search\u results=new Kitchon.Collections.searchList(响应); console.log(this.search_结果); this.search\u results.each(this.render\u match); } }, 渲染匹配:函数(模型){ console.log(模型) }, 这将返回一个错误 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 _byCid:对象 _byId:Object _onModelEvent:function(){[native code]} _removeReference:函数(){[本机代码]} 长度:7 型号:阵列[7] __原生动物:原生动物 我试过很多东西,但有一件突出的事情可能是我必须通过考试Collections backbone.js集合未响应。每个,collections,backbone.js,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.searc
this.search\u results.models.each(this.render\u match)
因为这是实际的数组,但是如果我这样做,我会得到一个未捕获的类型错误:Object[Object Object],[Object Object],…
只是在这里尝试一下(我对Backbone.js一无所知),但这不是你想要的:
$.each(this.search_results, function(index, value) {
alert(index + ': ' + value);
});
祝您好运!当调用每个方法的回调函数时,您将丢失执行上下文 在传递回调时使用
\uu.bind(this.render\u match,this)
确保render\u match
具有正确的上下文
您得到错误是因为您也没有包装getJson
方法的回调函数。您还必须使用下划线bind
方法
您应该阅读一些有关javascript的内容,以及如何驯服它-在这里试试
正确的代码应该大致如下所示
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)
},
虽然从我看到的情况来看——我假设您在这里展示的代码是一个模型或集合——正在处理呈现视图的操作——您不应该这样做!模型和集合仅用于存储和解析数据——所有呈现和控制应用程序流的操作都应该在视图(控制器)中完成在路由器的帮助下。$。getJson
更改此
引用。jquery中的许多方法都会这样做,因此此的值。render\u match
为空。将空值传递给每个
,则会失败
要解决此问题,请在$之前创建对此的引用(如var\u this=this;
)。getJson
并使用它而不是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)
},
Backbone.js正在将许多underline.js方法映射到集合-当您手头有underlinejs时,您不需要也不应该每次都使用jquery-它的实现速度更快+这一点。search\u results不是一个真正的数组,而是Backbone.Collection实例-如果您想直接在模型上迭代,您需要访问集合上的models
属性。您在每个循环中再次丢失了此
上下文-检查我的答案谢谢Tom,我知道“this”在某种程度上丢失了,但我不确定如何使其工作。Yehuda的文章是一个很好的补充。很难搜索“this”并返回相关结果。