这是一个 JSBin 来说明我遇到的问题。
我正在使用依赖注入来对 API 进行轮询机制,就像这样
App.Poller = Ember.Object.extend({
interval: function() {
return 1000;
}.property().readOnly(),
schedule: function(f) {
return Ember.run.later(this, function() {
f.apply(this);
this.set('timer', this.schedule(f));
}, this.get('interval'));
},
stop: function() {
this.set('running', false);
Ember.run.cancel(this.get('timer'));
},
start: function() {
if (!this.get('running')) {
this.set('running', true);
this.set('timer', this.schedule(this.get('onPoll')));
}
},
onPoll: function() {
Ember.Logger.log('basic poller overwrite with your method');
}
});
App.register('poller:main', App.Poller);
App.inject('route', 'poller', 'poller:main');
App.inject('controller', 'poller', 'poller:main');
这样我就可以从我的路由和控制器调用开始和停止轮询。
我设置了父路由,以便它像这样间歇性地轮询服务器以获取父路由中的进度(请注意,获取语法来自 Ember Data beta 12,但工作正常)
App.ParentRoute = Ember.Route.extend({
setupController: function(controller, model) {
store = this.store;
controller.set('model', model);
this.poller.reopen({
onPoll: function() {
return store.fetch('mymodel', 1);
}
});
},
model: function() {
return this.store.find('mymodel', 1);
}
});
我有各种子路由作为步骤过程的一部分,这取决于从 API 轮询接收的数据,所以在子控制器中我设置了这样的观察者
App.ParentChild1Controller = Ember.Controller.extend({
needs: ['parent'],
progress: Ember.computed.alias('controllers.parent.progress'),
pollingChild1: function() {
progress = this.get('progress');
Ember.Logger.log('called from pollingChild1 : ', progress);
if (progress < 50) {
this.poller.start();
} else {
this.transitionToRoute('parent.child2');
}
}.observes('progress').on('init')
});
它只是开始轮询,一旦进度超过 50 就转移到下一条路线。
我不明白为什么在转换到新路线后继续调用这个观察者?
如果您在路由更改时从该 JSBin 中查看控制台,它仍然被调用。
非常感谢任何关于为什么会发生这种情况的建议。