angularjs – Emberjs服务就像功能(像角度)?

前端之家收集整理的这篇文章主要介绍了angularjs – Emberjs服务就像功能(像角度)?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我有一个功能,每隔10秒与我的服务器通信,并且如果服务器说明的话,它会做一些事情(比如更新我的模型).

在角度我可以创建一个服务,定期做东西,同时仍然能够访问我的$scope(或$rootScope)我将如何在ember中做这样的事情?如何创建一个将在后台运行并将与我的ember应用程序集成的功能

我试图在ember文档中搜索类似于angular的服务,但到目前为止我在这条路线上没有运气:(

提前致谢 :)

解决方法

在应用程序路由中构建一个控制器,它实际上只是成为一个可以从所有路由/控制器访问的全局控制器.

在应用程序路由启动阶段构建

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的依赖注入)

使用容器,您可以急切地创建一个实例并将其附加到所有控制器,但是它不再是控制器(否则它会创建一个循环引用).

App.Service = Em.Object.extend({
  init: function(){
    this._super();

    this.startFooConsole();
  },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","my:service");
      // you also could put it in the app namespace
      application.service = service;
    }
});

http://emberjs.jsbin.com/bukuvuho/2/edit

猜你在找的Angularjs相关文章