我想知道是否有人可以帮助找出这种情况下的问题所在。 我在第 6 行收到“Uncaught ReferenceError: text is not defined”。 在 API 可用之前,使用模板和本地 .txt 文件进行测试。
Backbone.js 模型脚本:
var Letter = Backbone.Model.extend( {
urlRoot: 'data/json/news',
initialize: function() {
},
defaults: {
_type: "",
text: "",
is_read: 0
}
});
var News = Backbone.Collection.extend({
model: Letter,
url: 'data/json/list_news.txt',
initialize: function() {
},
fetchMyNews: function() {
this.fetch({async:false});
}
});
var news = new News();
查看脚本:
var NewsView = Backbone.View.extend({
initialize: function() {
this.isShown = false;
this.render();
this.listenTo(news, "all", this.doListen);
},
doListen: function(eventName){
if(eventName == "change"){
this.render();
}
},
isShown: false,
events: {
},
render: function() {
this.$el.attr("z-index", "1000");
news.fetchMyNews();
var sHtml = JST["news/row"](news.attributes);
$("#news_tbody").html(sHtml);
}
});
代码中的一些内容。
您正在为您的收藏定义一个全局变量“新闻”。不推荐这样做,您可以在实例化时将一个新集合传递给您的视图:
var NewsView = new NewsView({
collection: new News()
});
并将视图中的所有“新闻”引用更改为“this.collection”
而且,我通常不喜欢异步 ajax 调用。尝试将它们更改为回调,或者只是在您的视图中收听事件。哦,还有,尽量不要在 render() 中获取数据。你的函数应该只做它们被命名的事情。 :)
所以在你看来:
initialize: function() {
this.isShown = false;
this.listenTo(this.collection, "all", this.doListen);
this.collection.fetch();
},
doListen: function(eventName){
if(eventName == "change" || eventName == 'reset'){
this.render();
}
}
在你的渲染中:
var sHtml = JST["news/row"](new.attributes);
$("#news_tbody").html(sHtml);
你正在调用 news.attributes,这里的 news 是一个集合......“attributes”不会给你任何东西。我不确定您的模板是什么样子,但您可能在模板中调用了“.text”,由于 news.attributes 未定义,因此此处会出现此错误。