设置和拆解(以及自我失效)EmberJS视图

时间:2011-12-20 02:01:09

标签: sproutcore ember.js

我希望能够为EmberJS中的视图设置和拆除功能,对于这个例子我会说显示每5秒通过AJAX获取的日志,但这是我遇到的问题很多

我在这里创建了一个switchView方法来处理setup / teardown事件,但是现在它无法使自己无效以显示更新的信息。

Em.Application.create({

  wrapper: $('#content'),
  currentView: null,

  ready: function() {

    this._super();

    this.self = this;

    Em.routes.add('/log/', this, 'showLogs');
    Em.routes.add('*', this, 'show404');

  },

  switchView: function(name, view) {

    if (this.currentView) {
      $(document.body).removeClass('page-' + this.currentView.name);

      if (this.currentView.view.unload) {
        this.currentView.view.unload();
      }

      this.currentView.view.remove();
    }

    if (name) {
      $(document.body).addClass('page-' + name);
    }

    if (view.load) {
      view.load();
    }
    view.appendTo(this.wrapper);
    this.currentView = {name: name, view: view};
  }

});


var LogView = Ember.View.create({

  templateName: 'logs',

  logs: [],

  load: function() {
    var self = this;
    this.interval = setInterval(function() {
      self.fetchLogs.apply(self);
    }, 5000);
    this.fetchLogs();
  },

  unload: function() {
    clearInterval(this.interval);
  },

  fetchLogs: function() {
    var self = this;
    $.get('/logs', function(data) {
      self.logs = data.list;
    });
  }

});

2 个答案:

答案 0 :(得分:3)

我不是100%明确你要求的内容,但你应该调查willInsertElementdidInsertElementwillDestroyElement。这些都是相对于视图元素从DOM中插入和删除而调用的。

答案 1 :(得分:0)

您可以在RunLoop的末尾执行此操作:

Ember.run.schedule('timers', function () {
   //update your widget
});

http://blog.sproutcore.com/the-run-loop-part-1/。 EmberJS中存在相同的概念