Pergunta

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

    },
Foi útil?

Solução

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

Outras dicas

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

Just do

setTimeout(this.asyncRender, 5000);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top