根据您的代码,App.EventsController
有一个事件列表,现在让我们说我们希望 UI 显示一个事件列表,并且对于每个事件说我们希望视图有一个删除按钮,该按钮在用户单击时删除事件
完成的一种方法是使用Ember.CollectionView
,顾名思义,集合视图是针对此类需求量身定制的,在许多 Ember 示例中,未定义视图的使用,因为 ember 会为您自动生成它,但在某些情况下我们可能需要明确定义一个视图来满足我们的要求
App.EventsView = Ember.CollectionView.extend({
// It needs a list of data to iterate upon
// We are binding it to the controllers content data which
// is a list of events
contentBinding: "controller.content",
appendSpan: function(){
view = Ember.View.create({tagName: 'span'});
this.get("childViews").forEach(function(child){
view.appendTo(child);
});
},
// Now we need to also define a view template that will be
// generated for all the elements in the content array
// This could in turn be another collection view if required
// I am going to keep it simple for now
itemViewClass: Ember.View.extend({
templateName: "event",
deleteEvent: function(){
// Implement Delete
this.get("content").deleteRecord();
},
notifyUser: function(){
// The record doesn't get deleted as soon as user clicks, the request goes to
// server and server deletes the record and sends back the response to the
// client, Hence I'm using an observer here on isDeleted property of the record
if(this.get('content.isDeleted')){
alert("Record deleted Successfully");
}
}.observes('content.isDeleted')
})
})
重要说明CollectionView定义this.get("content")
中指的是事件数组,而itemViewClass中指的 this.get("content")
是单个事件对象
//Defining the template
//Assuming the event model has a name property
<script type="text/x-handlebars" data-template-name="event">
Name: {{view.content.name}}
<a {{action deleteEvent target="view"}} href="#">Delete Event</a>
</script>
现在,当您点击 application_url/events 时,您将看到一个事件列表,每个事件都有一个删除按钮,我希望这可以清除一些概念
有关CollectionView的更多信息
根据评论更新:
如果要为每个子视图附加另一个视图,可以通过编辑 itemViewClass 的模板来实现,如下所示
<script type="text/x-handlebars" data-template-name="event">
Name: {{view.content.name}}
<a {{action deleteEvent target="view"}} href="#">Delete Event</a>
{{ view App.SomeOtherView }}
</script>
它也可以是部分的,如下所示
<script type="text/x-handlebars" data-template-name="event">
Name: {{view.content.name}}
<a {{action deleteEvent target="view"}} href="#">Delete Event</a>
{{ partial "somePartial" }}
</script>
或者,如果您想以编程方式执行此操作,请单击 EventsView 模板中的一个按钮,然后单击所有子视图必须附加一个 span 标签(我不擅长举例)
//This is the template for App.EventsController,
//template-name = "events" => view is App.EventsView and controller App.EventsController
<script type="text/x-handlebars" data-template-name="events">
<a {{action appendSpan target="view"}} href="#"> Append </a>
</script>
appendSpan
在 CollectionView 中定义