我的 emberjs 应用程序中有一个没有任何数据库数据的模型。我创建了这个模型,因为我想要一些对象来汇集来自服务器的一些请求,但没有绑定到控制器或视图。
就像是:StatusChecker
在我的 Application.create 中,我这样做:
Webapp = Ember.Application.create({
rootElement: '#content',
LOG_TRANSITIONS: true,
ready: function() {
return Webapp.status_helper = Webapp.StatusHelper.create({
timer: 15
});
}
});
这将实例化一个Webapp.StatusHelper
对应用程序来说必须唯一的对象。当我调用init
这个对象时,我还使用默认计时器开始轮询:
Webapp.StatusHelper = Ember.Object.extend({
init: function(params) {
this.timer = this.get("timer");
this.timeoutID = null;
this.controller = null;
this.start();
},
start: function() {
this.execute();
},
stop: function() {
clearTimeout(this.timeoutID);
},
setTimer: function(newTime) {
this.stop();
this.timer = newTime;
this.start();
},
execute: function() {
var $this = this;
this.stop();
$.get("/status").done(function(data) {
console.log(data);
if (data["status"] === 0) { // Continue trying
$this.timeoutID = setTimeout(function() {
$this.execute();
}, $this.timer * 1000);
} else if (data["status"] === 1) { // Go to a given controller
$this.setTimer(15);
$this.transitionToRoute('index'); // This doesn't work
} else {
$this.setTimer(15);
$this.transitionToRoute('problem'); // This doesn't work
}
});
}
});
第一个问题是我无法使用以下方法更改模型的路线:$this.transitionToRoute('problem');
。有没有办法从模型中做到这一点?
第二个问题是,有时当我进入控制器时,我需要StatusHelper
在我需要停止该计时器并以另一个间隔启动它之后指定正确的间隔,如下所示:
Webapp.IndexRoute = Ember.Route.extend
setupController: (controller) ->
Webapp.status_helper.setTimer 15
Webapp.ProblemRoute = Ember.Route.extend
setupController: (controller) ->
Webapp.status_helper.setTimer 1
发生这种情况是因为我需要检查问题是否每秒钟都得到解决,并且索引页面会在需要时转换到问题页面。过渡后,我得到 2 个,有时甚至更多的间隔来从事同一项工作。
我怎样才能停止它并只使一个功能起作用?
PS:如果您发现我需要用其他东西更改模型,我可以更改它。
tl;博士
- 如何从控制器内部更改路由?
- 我怎样才能让一个函数以间隔运行?
- 还有另一种(更好的)方法吗?
编辑
我的图书馆版本:
DEBUG: Ember.VERSION : 1.0.0-rc.1 ember.js:348
DEBUG: Handlebars.VERSION : 1.0.0-rc.3 ember.js:348
DEBUG: jQuery.VERSION : 1.9.1