It is time! Time to talk Handlebars and how to use them in Ember.js or how Ember uses Handlebars.
If you want to follow along, get a copy of the Ember Starter Kit.
Open up the app.js and add the following code right before the App.Router.
App.personController = Ember.ArrayController.create({
content: [{name: 'Adam'}, {name: 'James'}]
});
(we are creating (create();) an instance of a class, therefor we use a lower case – personController, while when extending (extend();) a class we use a capital letter)
Here we are creating a controller naming it personController, and setting its content to some static content.
In your index.html put the following right after the body.
<script type="text/x-handlebars">
{{#each App.personController}}
<p>{{name}}</p>
{{/each}}
</script>
The ‘each’ loops through the content in the personController and outputs each name. The ‘#’ means start of the handlebar view and ‘/’ is the end point.
Run the app and it should output:
Adam
James
The Bonus part
To enhance the app somewhat we add a model. Right before the personController add:
App.Person = Em.Object.extend({
name: null
});
This adds a new model, class (whatever you want to call it). Setting a name and setting it to null is not necessary but it can help to remember what properties the model exists of(f)(?) <- (hey I'm swedish).
Add this to your personController:
init: function() {
this._super();
var person = App.Person.create({
name: ‘Linda’
});
this.pushObject(person);
}
this._super(); calls the parent class (super is a reserved to JavaScript hence the underscore _ ) and you need to do this inside the init so the init method will be called all the way up the prototype chain. (source Cerebris)
Then we create a instance (person) of the class Person and set its name property to 'Linda' and finally push (add) this to the content array.
Running the app should yield the following result:
Adam
James
Linda
Unsolved issue
Doing a console.log() last in init reveals the following:
The first two are objects but the last one is 'c', the one we created from a class, stand s for class?
