如何制作在视图层次结构中冒泡的自定义事件?

时间:2012-10-16 15:25:13

标签: ember.js

我有按钮视图,它是我写的一组Ember.js表单助手的一部分。例如。 MyAddressFormView具有以下模板:

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

要处理“提交”按钮,我让“提交”表单事件气泡,并在MyAddressFormView的submit方法中处理它。

但是如何对“取消”按钮执行相同操作?例如,有什么方法可以在子视图中触发自定义“取消表单”事件,让它冒泡,并在祖先视图中处理它?<​​/ p>

2 个答案:

答案 0 :(得分:4)

我建议触发jQuery特殊事件并使用Ember应用程序上的映射注册事件。例如:

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

在你的cancelButton视图中:

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

这将以与其他映射的Ember DOM事件相同的方式冒泡。

答案 1 :(得分:0)

Ember.ActionHandler通过其“target”属性冒泡事件。可以覆盖Ember.View的目标,默认情况下让事件通过parentViews冒泡。

首先包含此mixin:

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

然后就像你通常那样发送事件:

tap: function() { this.send('someEvent'); }
相关问题