How can I make custom events that bubble through the view hierarchy?

孤街浪徒 提交于 2020-01-01 12:49:26

问题


I have button views that are part of a set of Ember.js form helpers I wrote. E.g. MyAddressFormView has the following template:

{{#form}}
  {{textArea address}}
  {{submitButton}}
  {{cancelButton}}
{{/form}}

To handle the "Submit" button, I let the "submit" form event bubble, and handle it in the submit method of MyAddressFormView.

But how do I do the same for the "Cancel" button? For instance, is there any way I can trigger a custom "cancel form" event in a child view, let it bubble, and handle it in an ancestor view?


回答1:


I would suggest triggering a jQuery special event and registering the event with a mapping on your Ember app. For example:

Ember.Application.create({
  customEvents: {
    // key is the jquery event, value is the name used in views
    formcancel: 'formCancel'
  }
});

And in your cancelButton view:

click: function(evt){
  Ember.$().trigger('formcancel')
}

This will bubble in the same way that other mapped Ember DOM events do.




回答2:


Ember.ActionHandler bubbles events through its "target" property. It's possible to override Ember.View's target to let events bubble through parentViews by default.

Include this mixin first:

(function() {
    Ember.View.reopen({
        // Let actions bubble to parentView by default.
        target: function() {
            return this.get('parentView');
        }.property('parentView')
    });
})();

Then just send the event like you'd normally do:

tap: function() { this.send('someEvent'); }


来源:https://stackoverflow.com/questions/12918112/how-can-i-make-custom-events-that-bubble-through-the-view-hierarchy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!