2012-02-21 55 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

相關問題