11
我開始學習Ember,並不清楚什麼是處理事件的最好的,最可接受的,甚至是預期的方法。是否可以在點擊函數事件參數中檢查目標,是否應爲每個需要{{action}}以外的事件的項目創建新視圖,或者完全不同?在Ember.js中處理事件的最佳方式是什麼?
我開始學習Ember,並不清楚什麼是處理事件的最好的,最可接受的,甚至是預期的方法。是否可以在點擊函數事件參數中檢查目標,是否應爲每個需要{{action}}以外的事件的項目創建新視圖,或者完全不同?在Ember.js中處理事件的最佳方式是什麼?
IMO你應該儘可能使用{{action}}
助手。如果您想在模板中的標籤上附加事件,請使用{{action}}
;沒有必要作出一個新的觀點:
<a {{action showPosts href=true}}>All Posts</a>
<form {{action validate target="controller"}}>
// ...
</form>
上面的一個例外是當你要處理一個特定的元素上有多個事件:
// Template
<ul>
{{#each post in controller}}
{{#view App.PostView}}
{{title}}
{{#if view.showDetails}}
<span>{{summary}}</span>
{{/if}}
{{/view}}
{{/each}}
</ul>
// View
App.PostView = Ember.View.extend({
tagName: li,
classNames: ['post-item'],
mouseEnter: function(event) {
this.set('showDetails', true);
},
mouseLeave: function(event) {
this.set('showDetails', false);
}
});
因爲我們需要同時捕獲mouseEnter
和mouseLeave
(分別顯示和隱藏帖子的詳細信息),最好在View中執行,避免模板中的邏輯太多。對於上述的另一種方法是使用盡可能多的嵌套的標籤,因爲我們要處理的事件數(在本例中,2):
// Template
<ul>
{{#each post in controller}}
<li class="post-item" {{action showTheDetails post on="mouseEnter" target="controller"}}>
<span class="dummy" {{action hideTheDetails post on="mouseLeave" target="controller"}}
{{title}}
{{#if post.showDetails}}
<span>{{summary}}</span>
{{/if}}
</span<
</li>
{{/each}}
</ul>
然後在控制器:
// Controller
App.PostsController = Ember.ArrayController.extend({
showTheDetails: function(event) {
var post = event.context;
post.set('showDetails', true);
},
hideTheDetails: function(event) {
var post = event.context;
post.set('showDetails', false);
}
});
但我認爲你會同意這是醜陋的。請參閱here。
在要使用灰燼控制視圖(Ember.TextField,Ember.TextArea等),你別無選擇,只能捕捉到在觀看賽事的情況。 FYI
// Template
<legend>Add a comment</legend>
{{view App.CommentInputField valueBinding="comment"}}
// View
App.CommentInputField = Ember.TextField.extend({
focusOut: function(event) {
this.get('controller').validateComment();
},
keyDown: function(event) {
if (event.keyCode === 13) { // Enter key
this.get('controller').createComment();
return false;
}
}
});
:所以你在查看擴展控制視圖,並定義事件處理程序事件,如'mouseEnter'或'mouseLeave'不應由動作助手(見HTTPS討論處理:// github上.com/emberjs/ember.js/issues/1011和具體評論https://github.com/emberjs/ember.js/issues/1011#issuecomment-6367539) – pangratz
好吧,所以最後如果你有很多{{action}}幫助器方法不適合的事件,您最終會看到不少的視圖。 – TestDemoTest