Click here to Skip to main content
Click here to Skip to main content

Hello World using Ember.js

By , 28 Jun 2012
 

Introduction

Ember.js is a new JavaScript MVC framework, like Backbone or Knockout.  This is a very simple, Hello World introduction to Ember.js.

Background 

You should be familiar with the concept of MVC frameworks.  If you're not then don't worry, there are STACKS of them available. 

Ember.js

Okay, so Ember provides a framework to support MVC. It uses Handlebars.js to provide the view templating, and this is all fully integrated with the library so you don’t need a separate install. 

One word of advice – make sure to grab the DEBUG version of the code. This comes crammed with asserts, comments and if you go wrong then you’ll know why. 

So let’s get started. 

Create your HTML 

Views use the Handlebars template syntax. These are parsed in runtime by the Ember framework, and churn out HTML. Just like how Active Server Pages work, only all working on the client.

Create your view like so: 

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript">
</script>
<script type="text/javascript" src="http://www.codeproject.com/scripts/ember.min.js"></script>
</head>
<body>
<script type="text/x-handlebars">
{{#view App.UserView }}
<b>Name:</b> {{name}}
{{/view}}
</script>
 
<button onclick="btnTest_OnClick()" id="btnTest">Click me to change</button>
 
</body>
</html> 

The above is your entire HTML page. The view is inserted INLINE in the HTML document, and will appear there. In Ember, you can give views names, and have them appear dynamically, but we’re going to keep things as simple as possible here. 

You’ll see that the view has a bit of magic syntax – {{ and }} is handlebars syntax. #view App.UserView refers to the instance of the view object – we haven’t created that yet so don’t worry. {{ name }} is a databound element. 

Ember Model, View and Controller 

Now we’re ready to create our MVC triad. All of this is done within script tags. Ember requires an application namespace, so the first thing we do is create that. 

window.App = Ember.Application.create(); 

Next we create the model, and an instance, as so: 

App.Person = Ember.Object.extend({
  id: 0,
  name: ""
});
 
var person = App.Person.create();
person.name = "Duncan";
person.id = 0;

In the above code, we’ve created a Person class, and an instance of that class.

Next we create the controller: 

App.userController = Ember.Object.create({
  content: person,
  changeModel: function () {
    this.content.set('name', 'Joe');
  }
});

The convention is that the controller has a field called content, which is a reference to the data it controls (in other words, its model). For the purposes of this example, I’ve added a changeModel function – no convention here – which simply changes the name of the model to Joe.

Note how it changes it – because we have constructed the model as an Ember.Object.extend, then we must use the setter to change the value of the name field.

Now we will create the View class:

App.UserView = Ember.View.extend({
  nameBinding: 'App.userController.content.name'            
}); 

We set up the binding here, so that if the controller’s model field ever changes, then this will be automagically updated in the view. Note the naming of this binding is important: it has to tie up with the {{ name }} field we created in the view template – Ember knows this and drops the “Binding” from the end.

Finally, let’s bind to the button declared in the above HTML so that we can do some updating:

function btnTest_OnClick() {
  App.userController.changeModel();
} 

When the user clicks the button, the controller will update its model. As you’ll see if you run this code, your page will update automatically – despite never having had to tell the HTML to update.

Summary 

This is a VERY basic intro to Ember, but it hopefully gives a 5-minute intro in order for you to evaluate whether you want to take things further. It’s early days but shows great potential to support really rich applications – with minimal boilerplate code. And you can use as much or as little of the framework as you like – as we’ve seen here. Hope it helps!

The full code is:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://www.codeproject.com/scripts/ember.min.js"></script>
</head>
<body>
<script type="text/x-handlebars">
{{#view App.UserView }}
<b>Name:</b> {{name}}
{{/view}}
</script>
<button onclick="btnTest_OnClick()" id="btnTest">Click me to change</button>
 
<script type="text/javascript">
    window.App = Ember.Application.create();
 
    function btnTest_OnClick() {
        App.userController.changeModel();
    }
 
    $(document).ready(function() {
 
        App.Person = Ember.Object.extend({
            id: 0,
            name: ""
        });
 
        var person = App.Person.create();
        person.name = "Duncan";
        person.id = 0;
 
        App.userController = Ember.Object.create({
            content: person,
            changeModel: function () {
                this.content.set('name', 'Joe');
            }
        });
 
         App.UserView = Ember.View.extend({
            nameBinding: 'App.userController.content.name'            
        });
 
   });
 
</script>
 
 
</body>
</html> 

History

  • 28 June 2012 - Original revision.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Duncan Gunn
Architect BinaryForge Software Ltd.
United Kingdom United Kingdom
Member
Duncan is Principal Architect at BinaryForge Software Ltd, based in Sussex, England. He has over 12 years experience in developing software applications of all sizes, and specializes in building bespoke database systems.
 
Throughout the years he has worked on large scale enterprise systems for household name clients.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionPage not found for the reference.memberc_dickson17 Mar '13 - 5:03 
http://www.codeproject.com/scripts/ember.min.js
Buggetting error [modified]memberLars Dolling28 Nov '12 - 22:15 
Hi,
 
exactly the (simple) example I was looking for. Unfortunately it throws errors when I try it. No text shows up (expect the button):
Uncaught TypeError: Object prototype may only be an Object or null
 
I'm using following libs
<script type="text/javascript" src="libs/jquery-1.8.3.js"></script>
<script type="text/javascript" src="libs/ember-1.0.0-pre.2.min.js"></script>


modified 29 Nov '12 - 6:48.

GeneralRe: getting errormemberLars Dolling29 Nov '12 - 4:34 
Ok, found the issue. It works fine with ember 0.9.5 - only issue with ember 1.0. probably a bug in the ember RC Big Grin | :-D
GeneralRe: getting errormembergusgibson23 Jan '13 - 5:53 
I got this error too - what fixed for me was putting in the latest handlebars (though i thought ember came with handlebars?)
So im trying the hello world, and when i hit the button "Joe" does not appear. I put in a breakpoint and the model/content does get changed to "joe", but "joe does not appear for me on page.
GeneralMy vote of 4memberThiago R. Santos28 Jun '12 - 7:16 
I realize it's a "hello world" type of article, but you could have shown computed properties, sub-classing, one way bindings as well as the regular binding that you've shown. I guess what kills it for me is that you have a button calling a method directly in the controller instead of a view action calling the controller (then you could have shown the {{action}} helper). It's OK for an intro but there's sooooo much more to be shown. Would like to see more tho
GeneralRe: My vote of 4memberDuncan Gunn28 Jun '12 - 7:34 
Hi Thiago
 
Thanks for the feedback - it's been kept deliberately simple as Ember is really such a vast framework I just wanted to keep it focused on the absolute minimum. That said I should have probably at least mentioned things like the {{ action }} helper so will update in due course.
 
Thanks!

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 28 Jun 2012
Article Copyright 2012 by Duncan Gunn
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid