简体   繁体   中英

Bind handlebars to application object in ember.js

Q: How do I bind handlebars to an application object variable, such that when that variable updates, the handlebar data on the screen updates also?

jsfiddle: http://jsfiddle.net/kQuVG/3/

Handlebars :

<script type="text/x-handlebars">
    {{App.Player.stats.basic}} Scrap
</script>
<button>Add Scrap</button>

JavaScript :

App.Player = Em.Object.create({
    stats:{
        basic: 10,
        premium: 20
    }
});    

$('button').click(function(){
    console.log(App.Player.stats.basic);
    App.Player.stats.basic += 10;
    console.log(App.Player.stats.basic);
});

The fiddle isn't even working, what I'd like to do is to click the button and add 10 onto the App.Player.stats.scrap value, and have that reflected in the output pane. Is this even the right way to be doing this?

Thanks in advance.

G

There are quite a few things wrong with the fiddle. You should always be using Ember's universal accessors when setting and getting properties on any object (even singletons and "App/Namespace global" properties). Ember also has specific naming conventions, like not using capital letters to start instances of objects ('people', not 'People'). And you should also probably use the target/action interface.

I've created a fiddle with these changes. http://jsfiddle.net/ud3323/Ac2hs/

Handlebars :

<script type="text/x-handlebars">
  {{App.playerObj.stats.basic}} Scrap <br />
  <button {{action "click" target="App.playerController"}}>Add Scrap</button>
</script>​

JavaScript :

var get = Ember.get, getPath = Ember.getPath, set = Ember.set, setPath = Ember.setPath;

App = Ember.Application.create();

set(App, 'playerObj', Object.create({
    stats:Ember.Object.create({
        basic: 10,
        premium: 20
    })
}));

set(App, 'playerController', Ember.Object.create({
    click: function(view) {
        getPath(App, 'playerObj.stats').incrementProperty('basic', 10);
    }
}));

You need to use a setter and not assign values directly. I've updated the fiddle with something that works.

http://jsfiddle.net/kQuVG/4/

Handlebars :

<script type="text/x-handlebars">
    {{App.Player.stats.basic}} Scrap
</script>
<button>Add Scrap</button>

JavaScript :

App.Player = Em.Object.create({
    stats:{
        basic: 10,
        premium: 20
    }
});    

$('button').click(function(){
    console.log(App.Player.stats.basic);
    App.Player.setPath('stats.basic',  App.Player.getPath('stats.basic') + 10);
    console.log(App.Player.stats.basic);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM