Event delegation for target

老子叫甜甜 提交于 2019-12-13 14:14:29

问题


In the following code, my click events delegate and all three 'click' handlers in my view hierarchy get fired.

However, I also want to fire 'edit' in my entire view hierarchy. 'edit' is simply the target of an element in my 'child' view.

Template

<script type="text/x-handlebars">
  {{#view App.GrandparentView}}
    {{#view App.ParentView}}
        {{#view App.ChildView}}
           <span {{action "edit" target="view"}}>Click Me</span>
        {{/view}}    
    {{/view}}
  {{/view}}
</script>

JavaScript

App.GrandparentView = Ember.View.extend({
  click: function() {
    console.log('Grandparent Click Fired!');
  },
  edit: function () {
   console.log('GrandParent edit fired');        
  }
});
App.ParentView = Ember.View.extend({
  click: function() {
    console.log('Parent Click Fired!');
  },
  edit: function () {
    console.log('Parent edit fired');        
  }

});
App.ChildView = Ember.View.extend({
  click: function() {
    console.log('Child Click Fired!');
  },
  edit: function () {
    console.log('Child edit fired');        
  }

});​

Is there no way to delegate the target handlers in the view hierarchy? What I dont want to do is this:

App.ChildView = Ember.View.extend({
  click: function() {
    console.log('Child Click Fired!');
  },
  edit: function () {
    console.log('Child edit fired');        
    this.get('parentView').edit(); //DO NOT WANT TO DO THIS.
  }
});​

Here is a jsFiddle as an example to test.


回答1:


It looks like the same question you've posted about a week ago. As far as I can see, such feature is not implemented in ember. The event is propagated to the view hierarchy, but the action name is lost, and the default click handler is triggered.

The only workaround I found is to reopen the Ember.View class itself, and override the click handler like this:

Ember.View.reopen({
  click: function(event){
    if(event.view !== this && this[event.actionName]){
        return this[event.actionName](event);
    }
  }
})

See the fiddle here:

http://jsfiddle.net/Sly7/zZyCS/



来源:https://stackoverflow.com/questions/13027124/event-delegation-for-target

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