Frustrating iteration
HTML
<script src="https://github.com/downloads/emberjs/ember.js/ember-0.9.5.js"></script>
<script type="text/x-handlebars" data-template-name="parent-view">
<h1>Simple array each</h1>
<ul>
{{#each content}}
<!-- No way to access subview -->
<li>{{title}}</li>
{{/each}}
</ul>
<h1>Using mapped list</h1>
{{#collection Ember.CollectionIterator contentBinding="content" tagName="ul" className="list"}}
<!-- Cannot normally access anything related to MyView here -->
{{#view _superView.subView itemBinding="content"}} <!-- note "item" instead of "this" -->
Alert {{item.title}}
{{/view}}
{{/collection}}
</script>
JavaScript
var App = Ember.Application.create();
Ember.CollectionIterator = Ember.CollectionView.extend({
/**
* Set a reference to the iterator's parent class
*
* @param {*} view
* @param {Object} attrs
* @returns Ember.View
*/
createChildView : function(view, attrs) {
var newView = this._super(view, attrs);
newView.set('_superView', this.get('parentView'));
return newView;
}
});
//parent view
var MyView = Ember.View.extend({
templateName : 'parent-view',
//optional: computed property below could be bound to controller directly
contentBinding : 'controller.content',
//view used with individual items
subView : Ember.Button.extend({
click : function() {
//Reference to MyView instance is now parentView.parentView.parentView
//which is a pain
alert(this.item.title + " clicked");
}
})
});
//Controller, responsible for instantiating its own views
var controller = Ember.ArrayProxy.create({
content : [
{title : 'Item A'},
{title : 'Item B'}
],
init : function() {
this._super();
var view = MyView.create({
controller : this
});
view.append();
}
});