I have a model, defined using $resource
, that I am successfully loading.
Each loaded instance is, as promised, an instance of the class I defined.
(The example below is from the Angular docs. In it, User.get
results in an object that is an instanceof User
.)
var User = $resource('/user/:userId', {userId:'@id'});
However, imagine each User comes over the wire like this:
{
"username": "Bob",
"preferences": [
{
"id": 1,
"title": "foo",
"value": false
}
]
}
I defined a Preference
factory that adds valuable methods to Preference
objects. But when a User loads, those preferences
aren’t Preference
s, naturally.
I attempted this:
User.prototype.constructor = function(obj) {
_.extend(this, obj);
this.items = _.map(this.preferences, function(pref) {
return new Preference(pref);
});
console.log('Our constructor ran'); // never logs anything
}
But it has no effect and never logs anything.
How can I make each item in my User
s’ preferences
array an instance of Preference
?
new User
myself for each loaded user, after taking care ofpreferences
? – Salvador