假设我有一个功能,每隔10秒与我的服务器对话,并且如果服务器说明的话,它会做一些事情(比如更新我的模型)。
在角度我可以创建一个服务,定期做东西,同时仍然能够访问我的$scope
(或$rootScope
)我将如何在余烬中做这样的事情?如何创建一个将在后台运行并将与我的ember应用程序集成的功能?
我试图在ember docs中搜索类似于角色服务的东西,但到目前为止我在这条路线上没有运气:(
提前感谢:)
答案 0 :(得分:6)
在应用程序路径中构建一个控制器,它实际上只是一个可以从所有路由/控制器访问的全局控制器。
App.ApplicationRoute = Ember.Route.extend({
beforeModel: function(){
// eagerly create the service controller instance, aka start the service
var service = this.controllerFor('service');
}
});
App.ServiceController = Em.Controller.extend({
init: function(){
this._super();
this.startFooConsole();
},
startFooConsole: function(){
Em.run.later(this, this.startFooConsole, 1000);
console.log('hello world');
},
helloWorld: function(){
console.log('hello world function');
}
});
this.controllerFor('service').helloWorld();
App.FooController = Em.Controller.extend({
needs:['service'],
someMethod: function(){
this.get('controllers.service').helloWorld();
}
})
http://emberjs.jsbin.com/bukuvuho/1/edit
使用容器,您可以急切地创建一个实例并将其附加到所有控制器,但它不再是控制器(否则它会创建一个循环引用)。
App.Service = Em.Object.extend({
init: function(){
this._super();
this.startFooConsole();
},
startFooConsole: function(){
Em.run.later(this, this.startFooConsole, 1000);
console.log('hello world');
},
helloWorld: function(){
console.log('hello world function');
}
});
App.initializer({
name: "service",
initialize: function (container, application) {
// eagerly create the service and add it to the controllers/routes
var service = application.Service.create();
application.register("my:service", service, {instantiate:false});
application.inject("controller", "service", "my:service");
application.inject("route", "service", "my:service");
// you also could put it in the app namespace
application.service = service;
}
});