[英]SetTimeout inside emberjs model
我在我的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:如果你发现我需要用别的东西改变模型我可以改变它。
我的库的版本:
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
第一个问题是我无法使用以下方法更改模型中的路径:$ this.transitionToRoute('problem');. 有没有办法从模型中做到这一点?
您不能/不应该从模型访问路由器。 无论何时你发现有必要这样做,这都是一个线索,也许你的写作代码可能不是一个模型。 在这种情况下, Webapp.StatusHelper
应该是一个控制器。 所以类似于:
Webapp.StatusController = Ember.Controller.extend({
//your code here
});
然后你可以摆脱init()App.ready()钩子,而是使用ApplicationRoute的setupController钩子来配置和启动计时器。 当然,既然你现在在控制器中,你将能够访问路由器。
我怎么能阻止它并只使一个功能起作用?
所以基本上你需要在转换到新路线时启动/停止计时器。 使用路由的activate
, deactivate
和setupController
挂钩可在路由更改时打开/关闭计时器。 这样,您可以确保计时器仅在您需要时运行。
Webapp.IndexRoute = Ember.Route.extend
activate: (controller) ->
this.controllerFor('status').setTimer 15
this.controllerFor('status').start()
deactivate: (controller) ->
this.controllerFor('status').stop()
Webapp.IndexRoute = Ember.Route.extend
activate: (controller) ->
this.controllerFor('status').setTimer 1
this.controllerFor('status').start()
deactivate: (controller) ->
this.controllerFor('status').stop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.