0

Experience: Newbie

I have initialize function like this

initialize: function(){
        this.listenTo(this.model, "change", this.asyncRender);
    }

I want to listen to changes periodically,like for every 5 sec

I want something like this

setTimeout(function(){
            this.listenTo(this.model, "change", this.asyncRender);
        }, 5000);

How to do this?

Update:

This is throwing error updateValues not defined

initialize: function(){
        this.listenTo(this.model, "change", this.asyncRender);
        setInterval(function(){
            this.listenTo(this.model, "change", this.updateValues);
            console.log("3 seconds");
        },3000)
    },

this is not throwing errors

initialize: function(){
        this.listenTo(this.model, "change", this.asyncRender);
        this.listenTo(this.model, "change", this.updateValues);

    },
Sasikanth
  • 3,045
  • 1
  • 22
  • 45

2 Answers2

1

You don't have to listen periodically. You just register once in the initialize. If anything changes in the model, this.asyncRender will be called.

Change here means any attributes set or removed or modified.

Try calling

this.model.set("title", "A Scandal in Bohemia");

and see this.asyncRender be called.

EDIT: If you want to manually poll for every 5 minutes, then you can check this.model.changed property. This is not advisable though.

http://backbonejs.org/#Model-changed

initialize: function() {
  var self = this;
  window.setInterval(function() {
    if (self.model.changed) {
      // Do your stuff
      // this.asyncRender();
    }
  }, 5000);
}
Bharathwaaj
  • 2,627
  • 2
  • 22
  • 35
  • I want to listen for every 5 seconds, In my app, changes happens in every millisecond, i don't want to execute this every time, i want to execute only after 5 seconds – Sasikanth Apr 20 '14 at 13:01
  • You can setTimeout to check this.model.changed property. If it is true, then the model is changed. Check http://backbonejs.org/#Model-changed – Bharathwaaj Apr 20 '14 at 13:47
1

Then you don't have to register model.change event ...

Just do

setTimeout(this.asyncRender, 5000);
addisu
  • 634
  • 1
  • 4
  • 12