加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:31:34 所属栏目:安全 来源:网络整理
导读:假设我有一个功能,每隔10秒与我的服务器通信,并且如果服务器说明的话,它会做一些事情(比如更新我的模型). 在角度我可以创建一个服务,定期做东西,同时仍然能够访问我的$scope(或$rootScope)我将如何在ember中做这样的事情?如何创建一个将在后台运行并将与我
假设我有一个功能,每隔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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读