konclave
konclave

Reputation: 678

Can Emberjs computed property depends on other model property?

I have a model:

app.ObjectOne = Em.Object.extend({
    id: null,
    count: null
});

And another model, which computed property 'SomeProperty' I want to depend on property 'count' from ObjectOne

app.ObjectTwo = Em.Object.extend({
    id: null,
    someProperty: function(){
      return count+5;
    }.property('app.SomeObjectController.count')

});

So, can I do it that way? Or is there any other way to do it;

The main idea is that data of ObjectOne model comes after ObjectTwo, so I what to recompute property and rerender view

Upvotes: 3

Views: 1803

Answers (1)

sly7_7
sly7_7

Reputation: 12011

If I understand well, the behavior you want is exactly what Ember.js can bring to you.

First, here is a very basic template:

<script type="text/x-handlebars">
  Here, the template is updated each time this property is updated (equivalent to bound property)
  {{App.objectTwo.someProperty}}
</script>​

Here is the javascript. I don't know if you really want to use an ObjectController here, but you mention it, so I have use it. An ObjectController's act as a proxy around it's content property. That means here that someObjectController.get('count') will try to get the count property from the controller itself, and if it does not exist, then the controller retrieve the count property from its content.

App = Ember.Application.create();
App.someObjectController = Ember.ObjectController.create();

App.ObjectOne = Em.Object.extend({
  id: null,
  count: null
});
App.objectOne = App.ObjectOne.create({
  id: 1,
  count: 42
});
App.someObjectController.set('content', App.objectOne);

App.ObjectTwo = Ember.Object.extend({
  id: null,
  someProperty: function(){
    return App.someObjectController.get('count')+5;
  }.property('App.someObjectController.count')
});
App.objectTwo = App.ObjectTwo.create({
  id: 1
});

//in 3 seconds the count property is set to 0. You can see the template is updated
Ember.run.later(function(){
   App.objectOne.set('count', 0);
},3000);

Here is the working jsfiddle: http://jsfiddle.net/Sly7/M3727/4/

Upvotes: 2

Related Questions