Ember从普通Javascript调用动作处理程序

时间:2014-08-22 07:17:53

标签: javascript ember.js

我使用现有的jQuery在Ember工作。现在我需要从我的jQuery方法中调用我的路由器中的动作处理程序。

我的路线:

App.ApplicationRoute: Ember.Route.extend({
    actions: {
        updateFolder: function(obj){
             //Need to update my model using the obj.
        }
    }
});

我的JavaScript方法:

// Native Javascript code. 
function updateFolderModel(obj){
    // Need to call the action handler in my application route. How to call from here.
} 

如何从普通的原生JavaScript方法调用Ember动作处理程序。

1 个答案:

答案 0 :(得分:1)

您不希望外部代码了解您的Ember应用程序。在这种情况下处理此问题的最佳方法是使用DOM事件。 DOM事件将成为您的Ember应用程序与外部世界之间的通信方式。有关此问题的一些文档,请参阅http://emberjs.com/api/classes/Ember.View.html#toc_responding-to-browser-events

例如

App.ApplicationView = Ember.View.extend({
  // See comment by @Wishy
  click: function() {
    this.send('actionThatWillBeSentToYourRoute');
  },
  /*
  didInsertElement: function() {
    var self = this;
    // Replace 'click' with a custom DOM event
    this.$().on('click', function() {
      Ember.run(self, function() {
        this.send('actionThatWillBeSentToYourRoute');
      });
    });
  }
  */
});

Ember.run是必需的,因为你想在Ember runloop中运行回调。请注意,注册自定义DOM事件比在http://emberjs.com/api/classes/Ember.Application.html#property_customEvents中更清晰。

然后在你的路线中你会有

App.ApplicationRoute = Ember.Route.extend({
  actions: {
    actionThatWillBeSentToYourRoute: function() { ... }
  }
});

请注意,您可以定义自己的自定义DOM事件,例如事件updateFolder。然后就可以了

function updateFolderModel(obj){
  $.trigger('updateFolder', obj);
}

我希望这有任何帮助!