문제

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

    },
도움이 되었습니까?

해결책

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

다른 팁

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

Just do

setTimeout(this.asyncRender, 5000);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top