Amanpreet
Amanpreet

Reputation: 128

Update Ember model with Computed properties

I have an Ember Object and its Instantiation, on calling the "updateName" method periodically the property value updates, but is NOT reflected in the template via "model". Any guesses on what am I doing wrong?

var App = Ember.Application.create();

App.Router.map(function(){
    this.route('application');
});

App.myData = Ember.Object.extend({
    name: 'luke',
    updateName: function(){
        this.set('name', Math.random(1,10)+'');
    },
    newName: function(){
        return this.get('name');
    }.property('name')
});

App.myDataObj = App.myData.create({});
setInterval( function(){ 
    App.myDataObj.updateName()
    console.log( App.myDataObj.get('newName') )
}, 5000 );

App.ApplicationRoute = Ember.Route.extend({
    model: function(){
        return {
            name: App.myDataObj.get('newName')
        };
    }
});

Output: Luke and thats it

Help Appreciated

Upvotes: 0

Views: 154

Answers (1)

intuitivepixel
intuitivepixel

Reputation: 23322

Disclaimer: this is not how things should be done in ember, for example you should use the template/route/controller tandem, and using Ember.run.later instead of setInterval etc. However, referencing the model in the template works, here is how you could achieve it:

Template:

<script type="text/x-handlebars">
  <h2>Application</h2>
  {{model.newName}}
</script>

App:

App = Ember.Application.create({
  ready: function() {
    console.log('App ready');
  }
});

App.myData = Ember.Object.extend({
  name: 'luke',
  updateName: function(){
    this.set('name', Math.random(1,10)+'');
  },
  newName: function(){
    return this.get('name');
  }.property('name')
});

App.myDataObj = App.myData.create();

setInterval( function(){ 
  App.myDataObj.updateName();
  console.log( App.myDataObj.get('newName') );
}, 5000 );

App.ApplicationRoute = Ember.Route.extend({
  model: function() {
    return App.myDataObj;
  }
});

Demo:

http://jsbin.com/ISoZIma/3/edit

Hope it helps.

Upvotes: 1

Related Questions