我无法弄清楚这里发生了什么:
var times;
var t;
$(document).ready(function(){
var timeObj = Backbone.Model.extend({
setTime: function(time){
this.time = time;
return 1;
},
getTime: function(){
return this.time;
},
addTime: function(minutes){
return new Date(this.time.getTime() + minutes*60000);
}
});
var timeCollection = Backbone.Collection.extend({
model: timeObj,
});
t = new timeObj();
var now = new Date();
times = new timeCollection();
t.setTime(now);
var outputView = Backbone.View.extend({
el: "#output",
collection: times,
render: function(html){
this.$el.html(html);
},
renderTimes: function(){
var that = this;
this.collection.each(function(model){
console.log("g");
console.log(model.getTime());
that.$el.append(model.getTime()+"<br>");
});
},
initialize: function(){
this.listenTo(this.collection,"add", this.renderTimes());
}
});
times.add(t);
var t30 = t.addTime(30);
var t2 = new timeObj();
t2.setTime(t30);
var output = new outputView();
times.add(t2);
}):
如果我将添加行放在输出创建上方,它确实有用。
这是应该如何工作还是我错过了什么?
答案 0 :(得分:2)
这里的语法错误很小:
this.listenTo(this.collection,"add", this.renderTimes());
应该是这个(基本上只需要删除因为函数调用将()
或null
返回给你的回调而导致你的回调搞乱的undefined
当你想要实际的函数时稍后回调):
this.listenTo(this.collection,"add", this.renderTimes);
这里还有一个jsFiddle修复:http://jsfiddle.net/a9YAV/
修改2
这是一个更新的jsFiddle,可以更好地说明事情:http://jsfiddle.net/a9YAV/1/
我改变的是:
initialize: function(){
this.listenTo(this.collection,"add", this.renderTimes);
this.renderTimes();
}
您需要确保在初始化时调用renderTimes
以加载初始元素
此处添加第二个时间对象也增加了一点延迟,以确保第二次调用renderTimes
:
setTimeout(function() {
times.add(t2);
}, 1000);