在Ember.js中的方法之间共享变量上下文

Sharing variable context between methods in Ember.js

本文关键字:之间 共享变量 上下文 方法 Ember js      更新时间:2023-09-26

我正在构建一个对象,该对象处理一种定时方法,以控制用服务器中的数据刷新模型。它非常简单。然而,我是Ember的新手,很难理解范围和上下文。

例如,当我创建这样一个对象时:

App.ModelRefresh = Ember.Object.extend({
  start: function(){
    this.timer = setInterval(this.refresh.bind(this), 2000);
  },
  stop: function(){
    console.log('stop');
    clearInterval(this.timer);
  },
  refresh: function(){
    console.log('refresh');
  }
});

然后在路由器中创建它来处理重新加载。再次如此:

App.PublishablesRoute = Ember.Route.extend({
  model: function() {
    return App.Publishable.fetch();
  },
  setupController: function(controller, model) {
    controller.set('model', model);
    var modelRefresh = App.ModelRefresh.create();
    modelRefresh.start();
  },
  deactivate: function() {
    modelRefresh.stop();
  }
});

在控制台中,我看到了错误。

Assertion failed: Error while loading route: ReferenceError: modelRefresh is not defined

我可以让它运行方法.start()而不用麻烦(显然)。但我可以运行.stop()。这是有道理的,但如何在不同的路由方法之间共享新创建的modelRefresh。在Backbone.js中,我会添加它来初始化并使用this引用父级。在Ember中,这似乎不起作用。

如有任何帮助,我们将不胜感激。

App.PublishablesRoute = Ember.Route.extend({
  model: function() {
    return App.Publishable.fetch();
  },
  setupController: function(controller, model) {
    controller.set('model', model);
    var modelRefresh = App.ModelRefresh.create();
    modelRefresh.start();
    this.set('modelRefresh', modelRefresh ); 
  },
  deactivate: function() {
    var modelRefresh  = this.get('modelRefresh');
    modelRefresh.stop();
  }
});

路由器激活和停用目前,每当Ember激活或停用路由处理程序时,许多人都会使用未记录的和私有的进出挂钩来运行代码

从Ember 1.0 RC1开始,有公共挂钩:激活和停用。请注意,只有在第一次激活路由处理程序时,activate钩子才会运行。如果路由处理程序的上下文发生更改,setupController钩子将再次运行,但不会运行activate钩子。

App.PublishablesRoute = Ember.Route.extend({
  model: function() {
    return App.Publishable.fetch();
  },
  activate: function() {
    $('#page-title').text("Publish");
    var modelRefresh = App.ModelRefresh.create();
    this.set('modelRefresh', modelRefresh );
    modelRefresh.start();
  },
  deactivate: function() {
    var modelRefresh  = this.get('modelRefresh');
    modelRefresh.stop();
  }
});

启动

init: function() {
  var modelRefresh = App.ModelRefresh.create();
  this.set('modelRefresh', modelRefresh );
  this._super();
},