简体   繁体   English

灰烬从普通的Javascript调用动作处理程序

[英]Ember call a action handler from normal Javascript

I am working in Ember with my existing jQuery. 我正在使用现有的jQuery在Ember中工作。 Now I need to call a action handler in my Router from my jQuery method. 现在,我需要从jQuery方法中的Router中调用操作处理程序。

My Route: 我的路线:

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

My JavaScript method: 我的JavaScript方法:

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

How can I call Ember action handlers from normal native JavaScript methods. 如何从普通的本机JavaScript方法调用Ember操作处理程序。

You don't want your outside code to know about your Ember application. 您不希望外部代码了解您的Ember应用程序。 The best way to deal with this in this case is using DOM events. 在这种情况下,解决此问题的最佳方法是使用DOM事件。 DOM events would be the means of communication between your Ember application and the "outside world". DOM事件将是Ember应用程序与“外部世界”之间进行通信的手段。 See http://emberjs.com/api/classes/Ember.View.html#toc_responding-to-browser-events for some documentation on this. 有关此文档的更多信息,请参见http://emberjs.com/api/classes/Ember.View.html#toc_responding-to-browser-events

For instance 例如

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');
      });
    });
  }
  */
});

The Ember.run is required because you want to run the callback inside the Ember runloop. Ember.run是必需的,因为您要在Ember运行循环中运行回调。 Note that it is a bit cleaner to register your custom DOM events as in http://emberjs.com/api/classes/Ember.Application.html#property_customEvents . 请注意,与http://emberjs.com/api/classes/Ember.Application.html#property_customEvents中的注册您的自定义DOM事件相比,这样做更为干净。

Then in your Route you would have 然后在您的路线中,您将拥有

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

Note that you can define your own custom DOM events, for instance an event updateFolder . 请注意,您可以定义自己的自定义DOM事件,例如事件updateFolder Then you can do 那你可以做

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

I hope this is of any help! 希望对您有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM