我有一个模型,使用$资源定义,我正在成功加载.
如所承诺的,每个加载的实例都是我定义的类的一个实例.
(下面的例子来自Angular文档,在其中,User.get导致一个objectof User的对象.)
var User = $resource('/user/:userId',{userId:'@id'});
但是,想像一下每个用户如下所示:
{
"username": "Bob","preferences": [
{
"id": 1,"title": "foo","value": false
}
]
}
我定义了一个Preference工厂,为Preference对象添加了有价值的方法.但是当用户加载时,这些首选项自然不是首选项.
我试过这个:
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
}
但它没有任何效果,也不会记录任何东西.
我如何使用户的首选项数组中的每个项目都是首选项的实例?
$资源是一个简单的实现,缺少这样的东西.
User.prototype.constructor不会做任何事情;与其他库不同,角度不会像面向对象那样尝试行事.这只是javascript
不幸的是,你有承诺和javascript :-).这是一种你可以做的方法:
function wrapPreferences(user) {
user.preferences = _.map(user.preferences,function(p) {
return new Preference(p);
});
return user;
}
var get = User.get;
User.get = function() {
return get.apply(User,arguments).$then(wrapPreferences);
};
var $get = User.prototype.$get;
User.prototype.$get = function() {
return $get.apply(this,arguments).$then(wrapPreferences);
};
您可以将其抽象为一种装饰资源方法的方法:它需要一个对象,一个方法名称数组和一个装饰器函数.
function decorateResource(Resource,methodNames,decorator) {
_.forEach(methodNames,function(methodName) {
var method = Resource[methodName];
Resource[methodName] = function() {
return method.apply(Resource,arguments).$then(decorator);
};
var $method = Resource.prototype[methodName];
Resource.prototype[methodName] = function() {
return $method.apply(this,arguments).$then(decorator);
};
});
}
decorateResource(User,['get','query'],wrapPreferences);