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

时间:2013-12-13 20:30:01

标签: javascript model-view-controller ember.js

我正在构建一个对象来处理一个计时方法,以控制使用服务器中的数据刷新模型。这非常简单。但是,我是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似乎不起作用。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

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开始,有公共挂钩:激活和停用。请注意,只有首次激活路径处理程序时,激活挂钩才会运行。如果路由处理程序的上下文发生更改,则setupController挂钩将再次运行,但不会再运行。

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

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