2014-02-07 98 views
1

我無法弄清楚是怎麼回事:視圖不更新的集合添加如果做視圖後創建骨幹

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); 

}): 

它的工作,如果我把輸出創建上面的附加線。

這是應該如何工作,或者我錯過了什麼?

回答

2

你有小的語法錯誤的位置:

this.listenTo(this.collection,"add", this.renderTimes()); 

應該是這個(基本上只需要刪除其搞砸你的回調,因爲函數調用返回要麼nullundefined到您的收聽,當你想要的()實際功能後回調):

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);