Question

The Code is from the ember.js official introduction:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title></title>
</head>
<body>
<script type="text/javascript" src="jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="ember-0.9.3.js"></script>
<script type="text/javascript">
    var App = Ember.Application.create();

    App.president = Ember.Object.create({
        name: "Barack Obama"
    });

    App.country = Ember.Object.create({
        presidentNameBinding: "App.president.name"
    });

    App.country.get("presidentName");
</script>
</body>
</html>

I was trying to display the return value of App.country.get("presidentName");,so i wrapped it with alert, but the alert always display undefined. The wired part is if i execute this statement in firebug console, it display correctly which is "Barack Obama".

The official introduction mentioned:

Note that bindings don't update immediately. Ember waits until all of your application code has finished running before synchronizing changes

Is this the reason why i can't get the value of the binding property in the code? What does "application code has finished running" actually mean?

Was it helpful?

Solution

When you're playing around with objects that have bindings like this, you have to manually trigger the bindings to sync with Ember.run.sync():

var App = Ember.Application.create();

App.president = Ember.Object.create({
    name: "Barack Obama"
});

App.country = Ember.Object.create({
    presidentNameBinding: "App.president.name"
});

Ember.run.sync(); // Manually sync bindings

alert( App.country.get("presidentName") );

Here's a jsFiddle with the example: http://jsfiddle.net/ebryn/3Ctns/

OTHER TIPS

You need to add an Observer that essentially fires after the initial application code runs.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title></title>
</head>
<body>
<script type="text/javascript" src="js/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="js/ember-0.9.3.js"></script>
<script type="text/javascript">
    var App = Ember.Application.create();

    App.president = Ember.Object.create({
        name: "Barack Obama"
    });

    App.country = Ember.Object.create({
        presidentNameBinding: "App.president.name"
    });

    App.country.addObserver('presidentName', function() {
        alert(App.country.get("presidentName"));
    });
</script>
</body>
</html>

Look for 'addObserver' in the ember.js introduction.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top