gpt4 book ai didi

collections - backbone.js 集合没有响应 .each

转载 作者:行者123 更新时间:2023-12-04 23:28:22 26 4
gpt4 key购买 nike

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

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

这将返回一个错误

未捕获的类型错误:未定义不是函数

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

_byCid:对象
_byId:对象
_onModelEvent: function () { [ native 代码] }
_removeReference: function () { [ native 代码] }
长度:7
模型:数组[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)
},

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

关于collections - backbone.js 集合没有响应 .each,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8865367/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com