Emberjs: Relative View Path
by ud3323
HTML
<script src="http://cloud.github.com/downloads/emberjs/ember.js/ember-0.9.4.js"></script>
<script type="text/x-handlebars">
{{#each App.projectController}}
{{#view App.ProjectListView contentBinding="this" controllerBinding="App.projectController"}}
{{content.name}} ({{content.source}})
<a href="#" {{action "linkSelected" on="click"}}>select</a>
{{/view}}
{{/each}}
<hr>
{{App.projectController.current.name}}
</script>
JavaScript
App = Ember.Application.create();
App.Project = Ember.Object.extend();
App.projectController = Ember.ArrayProxy.create({
content: [],
current: null
});
App.ProjectListView = Ember.View.extend({
linkSelected: function() {
// Sets App.projectController.current
this.get('controller').set('current', this.get('content'));
// If you don't want to specify the controller in the handlebars template
// for this view, you can do the following:
this.getPath('_parentView._parentView.content').set('current', this.get('content'));
// The above accesses the #each helper's content (grandparent to this view)
// which is App.projectController.
// Both statements work though I'd use the 1st statement to separate what
// we see as `content` and `controller` here. It increases reusability imho.
// Plus it's prettier code :)
}
});
//---- load it with data and make the last entry current ----
App.projectController.pushObject(
App.Project.create({ name: "jQuery", source: "jquery.js" }));
App.projectController.pushObject(
App.Project.create({ name: "Ember", source: "ember.js" }));
App.projectController.pushObject(
App.Project.create({ name: "Backbone", source: "backbone.js" }));
App.projectController.set('current', App.projectController.get('lastObject'));