shaneburgess
shaneburgess

Reputation: 15882

View not updating on collection add if done after view create in backbone

I am not able to figure out what is going on here:

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

}):

It does work if I put the add line above the output create.

Is this how it is supposed to work or am I missing something?

Upvotes: 1

Views: 49

Answers (1)

Gohn67
Gohn67

Reputation: 10638

You have small a syntax error here:

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

Should be this (basically just need to remove the () which messed up your callback since the function call returned either null or undefined to your listener when you wanted the actual function to callback later):

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

Also here is a jsFiddle with the fix: http://jsfiddle.net/a9YAV/

Edit 2

Here is an updated jsFiddle that illustrates things better: http://jsfiddle.net/a9YAV/1/

Change one I made was:

 initialize: function(){
     this.listenTo(this.collection,"add", this.renderTimes); 
     this.renderTimes();
 }

You need to make sure to call renderTimes in initialize to load the initial elements

Also added a small delay to adding the second time object here to make sure renderTimes was being called a second time:

setTimeout(function() {
    times.add(t2);     
}, 1000);

Upvotes: 2

Related Questions