Reputation: 185
So I have an Ember Object:
App.User = Ember.Object.extend({
firstName: null,
lastName: null,
dob: Ember.Object.create({
day: null,
month: null,
year: null,
display: function () {
var self = this,
day = (self.get('day') < 10 ? "0" : "") + self.get('day'),
month = (self.get('month') < 10 ? "0" : "") + self.get('month'),
year = self.get('year');
return day + '/' + month + '/' + year;
}.property('day', 'month', 'year')
})
});
And on my Controller - I am creating a version of the object - which is then bound to by a form:
App.IndexController = Em.ArrayController.extend({
user: App.User.create()
});
However - for some reason, whenever I try and get the dob.display computer property within my controller or in my view, I just get an object returned.
this.get('user.dob.display')
{{user.dob.display}}
Any ideas how to make sure it returns a string? This was working up until a couple of days ago when I updated from 1.0.0-pre2 to 1.0.0-pre4.
Upvotes: 0
Views: 1102
Reputation: 10726
You should not use create
, but createWithMixins
. This is the only way to define computed properties on object creation:
dob: Ember.Object.createWithMixins({
day: null,
month: null,
year: null,
display: function () {
day = (this.get('day') < 10 ? "0" : "") + this.get('day'),
month = (this.get('month') < 10 ? "0" : "") + this.get('month'),
year = this.get('year');
return day + '/' + month + '/' + year;
}.property('day', 'month', 'year')
})
One remark: when setting properties in extend
methods, each instance share the same object.
If you do not know that, go read "Understanding Ember.Object" article written by Dan Gebhardt (this article could be a little bit outdated, but the idea is still the same).
Consequently, here, you have:
var user1 = App.User.create().get("dob").set("year", 1988);
var user2 = App.User.create();
console.log(user2.get("dob.year")); // => 1988
If you want to define objects that are different between instances, you have to override the init
method like this:
App.User = Ember.Object.extend({
init: function() {
this._super(); // do not forget that
this.set('dob', Ember.Object.createWithMixins({
// [code ommitted]
}));
}
});
But I suggest you to create a model dob
instead of just create it each time you create a user.
You can try this in a JSFiddle.
Upvotes: 4
Reputation: 568
In pre4 you cannot define a computed property on a Ember.Object that is created.
Not allowed
dob: Ember.Object.create({
day: null,
month: null,
year: null,
display: function () {
var self = this,
day = (self.get('day') < 10 ? "0" : "") + self.get('day'),
month = (self.get('month') < 10 ? "0" : "") + self.get('month'),
year = self.get('year');
return day + '/' + month + '/' + year;
}.property('day', 'month', 'year')
})
It's only allowed to do this on Objects that is extended.
I have created a fiddle (abit modified) that works with your dob logic.
http://jsfiddle.net/Energiz0r/AeDAw/4/
Upvotes: 0