2012-02-21 88 views
6

考虑一个视图定义对象的列表:与模板如何将事件传递给父视图,传递触发事件的子视图?

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

    itemClicked: function(item){ 

    } 
)}; 

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

和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 
    } 
}) 

所以基本上我的问题是如何传递事件到父视图,特别是在父视图未被子视图所知的情况下?我知道您可以通过this.getPath('parentView').get('foo')this.getPath('contentView').get('foo')获得父视图的属性foo。但是一个函数怎么样(在这种情况下,itemclicked())?

回答

7

this.get('parentView').itemClicked(this.get('item'));应该这样做。

+0

我以为我测试,并没有奏效。我会让一个jsFiddle来测试它。我很确定'this.get('contentView')。itemClicked(this.get('item'));'(用于将事件传递给父母)不起作用。 – 2012-02-21 21:32:48

+0

@Zack它似乎在这里工作:http://jsfiddle.net/tomwhatmore/FGyrV/1/除非我误解了这个问题。可能是因为你使用'getPath()'而不是'get()'? – 2012-02-21 22:31:34

+0

Yeap,我正在使用getPath :) – 2012-02-22 06:09:01

3

可以使用{{action}}帮手,请参见:http://jsfiddle.net/smvv5/

模板:

<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({ 
});​ 
+1

这实际上是否在最新版本的Ember上工作? click事件似乎没有将任何参数传递给click方法。它只是未定义的'view','event'和'ctx' – Wasim 2013-10-29 12:52:34

0

最近灰烬的版本直接使用actions哈希,而不是方法上对象(虽然这个不推荐使用的方法仍然受支持,但可能不会很长)。如果您想要传递给处理程序的视图的引用,请将“view”作为参数发送,并使用parentView作为目标。

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

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

{{action}}助手不会通过事件对象发送。如果你需要的话,仍然不确定如何参考事件。

source

相关问题