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

Ember call a action handler from normal Javascript

本文关键字:一个 程序 处理 Javascript 调用 Ember      更新时间:2023-09-26

我正在用我现有的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动作处理程序?

您不希望外部代码知道您的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运行循环中运行回调。请注意,将自定义DOM事件注册为http://emberjs.com/api/classes/Ember.Application.html#property_customEvents会更简洁一些。

那么在你的Route中你应该有

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

注意,您可以定义自己的自定义DOM事件,例如事件updateFolder。然后你可以输入

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

我希望这是任何帮助!

相关文章: