Somehow I don't understand how to implement views which require a certain controller with ember.js. I'll try to explain the issue in which I run with an example:
Let's say I would like to build a view component which creates a simple todo list: It contains a textfield. Underneath of that field is a list of all todo items that have been entered so far. That view should have a controller which stores the todo items (since I don't have to push to store them persistent at that point).
I'd like the view to be usable in different places of the webapp (through my handlebars templates), so it should be independent of the route through which it is accessed.
My templates look like this:
<?xml version="1.0" encoding="utf-8"?>
<html>
<head>
<script src="../shared/libs/jquery-1.9.1.js"></script>
<script src="../shared/libs/handlebars-1.0.0-rc.3.js"></script>
<script src="../shared/libs/ember-1.0.0-rc.1.js"></script>
<script src="todo.js"></script>
</head>
<body>
<script type="text/x-handlebars" data-template-name="application">
{{ view App.TodolistView }}
</script>
<script type="text/x-handlebars" data-template-name="todolistView">
{{view App.CreateTodoTextField
placeholder="Enter your todo here"
size=100
}}
<ul>
{{#each todo in controller}}
<li>{{todo}}</li>
{{/each}}
</ul>
</script>
</body>
</html>
My App Logic looks like this:
window.App = Ember.Application.create();
App.TodolistView = Ember.View.extend({
templateName: 'todolistView'
});
App.TodolistController = Ember.ArrayController.create({
content: [],
createItem: function(item) {
this.pushObject(item);
}
});
App.CreateTodoTextField = Ember.TextField.extend({
insertNewline: function() {
var value = this.get('value');
if (value) {
App.TodolistController.createItem(value);
this.set('value', '');
}
}
});
I have two problems with that code:
When my TodolistView tries to access the controller with
{{#each todo in controller}}
it actually accesses the ApplicationController, not the TodolistController
Also calling
App.TodolistController.createItem(value);
looks like a bad idea to me: I.e. what if I would have two TodoListViews on one page? createItem should be rather called on the current instance of the TodolistController...
Probably I'm missing a core concept for defining views with ember.js...