Emberjs service as a function (e.g. angular)?

Let's say that I have a function that talks to my server every 10 seconds and will do things (for example, update my models) if the server says so.

In angular, I can create a service that will periodically do something while it can still access my $scope(or $rootScope), how will I do such a thing in ember? How can I create a function that will work in the background and integrate with my eber application?

I tried to find something similar to the angular service in ember docs, but so far I have been out of luck :(

early:)

+4
source share
1 answer

, , /.

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

(Ember Dependency Injection)

, , ( ).

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

+6

Source: https://habr.com/ru/post/1542342/


All Articles