How to pass events to a parent View, passing the child View that triggered the event?

StackOverflow https://stackoverflow.com/questions/9379345

  •  28-10-2019
  •  | 
  •  

Pergunta

Consider a View that defines a list of objects:

App.ListView = Ember.View({
  items: 'App.FooController.content'

  itemClicked: function(item){

  }
)};

with the template:

<ul>
{{#each items}}
    {{#view App.ItemView itemBinding="this" tagName="li"}}
      <!-- ... -->
    {{/view}}
{{/each}}
</ul>

and the ItemView:

App.ItemView = Ember.View.extend({

  click: function(event){

    var item = this.get('item');

    // I want to call function itemClicked(item) of parentView
    // so that it handles the click event
  }
})

So basically my question is how do I pass events to parent views, especially in the case where the parent view is not known by the child view? I understand that you can get a property foo of a parentView with either this.getPath('parentView').get('foo') or this.getPath('contentView').get('foo'). But what about a function (in this case, itemclicked())?

Foi útil?

Solução

this.get('parentView').itemClicked(this.get('item')); should do the trick.

Outras dicas

You can use the {{action}} helper, see: http://jsfiddle.net/smvv5/

Template:

<script type="text/x-handlebars" >
    {{#view App.ListsView}}
        {{#each items}}
            {{#view App.ListView itemBinding="this" }}
                <li {{action "clicked" target="parentView" }} >{{item.text}}</li>
            {{/view}}
        {{/each}}
    {{/view}}
</script>​

JS:

App = Ember.Application.create({});

App.Foo = Ember.ArrayProxy.create({
    content: [Ember.Object.create({
        text: 'hello'
    }), Ember.Object.create({
        text: 'action'
    }), Ember.Object.create({
        text: 'world'
    })]
});
App.ListsView = Ember.View.extend({
    itemsBinding: 'App.Foo',
    clicked: function(view, event, ctx) {
        console.log(Ember.getPath(ctx, 'item.text'));
    }
});
App.ListView = Ember.View.extend({
});​

Recent versions of Ember use the actions hash instead of methods directly on the object (though this deprecated method is still supported, it might not be for long). If you want a reference to the view passed to the handler, send through "view" as a parameter and use the parentView as the target.

<button {{action "onClicked" view target="view.parentView"}}>Click me.</button>

App.ListsView = Ember.View.extend({
    actions: {
        onClicked: function(view) {
        }
    }
});

{{action}} helper does not send through the event object. Still not sure how to get reference to the event if you need it.

source

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top