Emberjs service like feature(like angular)?
angularjs, ember.js
Solution
Build up a controller in the application route, which essentially then just becomes a global controller you can access from all of your routes/controllers.
Build during the application route startup phase
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');
}
});
Access from a route
this.controllerFor('service').helloWorld();
Access from a controller
App.FooController = Em.Controller.extend({
needs:['service'],
someMethod: function(){
this.get('controllers.service').helloWorld();
}
})
http://emberjs.jsbin.com/bukuvuho/1/edit
Build using the container (Ember's Dependency Injection)
Using the container you can eagerly create an instance and attach it to all of the controllers, but then it shouldn't be a controller anymore (else it creates a circular reference).
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;
}
});
http://emberjs.jsbin.com/bukuvuho/2/edit
Problem
Lets say I have a function that talks to my server each 10 seconds and will do stuff (like update my models) if the server tell it so. In angular I can create a service that will periodically do stuff while still be able to access my `$scope`(or `$rootScope`) how will I do such a thing in ember? how can i create a function that will run in the background and will be integrated with my ember app? I've tried to search in the ember docs something similar to angular's service but i had no luck in this route so far :( thanks in advance :)