2016-08-23 48 views
1

我有一个包含队列的服务。任何注入此服务的东西都可以将对象添加到服务的队列中。我需要该服务从该队列中异步删除项目,并运行它们。有一个像service.processQueue()那样调用的周期性函数会很好。这是一个适当的用例来使用Ember运行循环?我怎样才能永久地将它添加到Ember.RunLoop中,而不是只运行一次?Ember Run Loop澄清

编辑: 我注意到从文档两种方法:http://emberjs.com/api/classes/Ember.run.html#method_schedule

run.schedule('sync', this, function() { 
    // this will be executed in the first RunLoop queue, when bindings are synced 
    console.log('scheduled on sync queue'); 
}); 

将run.schedule永久添加这灰烬运行的循环?

function sayHi() { 
    console.log('hi'); 
} 

run(function() { 
    run.scheduleOnce('afterRender', myContext, sayHi); 
    run.scheduleOnce('afterRender', myContext, sayHi); 
    // sayHi will only be executed once, in the afterRender queue of the RunLoop 
}); 
+0

请显示您的示例代码..它对我至少有用... – kumkanillam

+0

我没有任何代码。我试图找出在浪费时间之前实施此服务的最佳方式。 – Taztingo

+0

@torazaburo - 好的,谢谢。 scheduleOnce和schedule之间有什么区别? – Taztingo

回答

3

做什么run.schedule是,它的时间表回调在一定队列一次运行。与run.scheduleOnce的区别在于,如果您将它传递给相同的函数两次,就像在您显示的文档中那样,它将只运行一次该函数。

在代码:

function sayHi() { 
    console.log("hi"); 
} 

run(function() { 
    schedule('afterRender', myContext, sayHi); 
    schedule('afterRender', myContext, sayHi); 
} 
// hi 
// hi 

run(function() { 
    run.scheduleOnce('afterRender', myContext, sayHi); 
    run.scheduleOnce('afterRender', myContext, sayHi); 
}); 
// hi 

如果要定期运行特定的功能,你想要的是一个递归函数,也就是说,自称在一组间隔的功能。你可以自己做,像tick function in this Twiddle example

tick: function() { 
    // ... 

    Ember.run.later(this, this.tick, 1000); 
}, 

或者你可以使用的插件,如ember-concurrency帮你安排吧。

+0

这是我正在寻找的答案。谢谢。 – Taztingo