如何擴充套件AngularJS資源($資源)的建構函式?
我有一個模型,使用$資源定義,我正在成功載入.
如所承諾的,每個載入的例項都是我定義的類的一個例項.
(下面的例子來自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);
http://stackoverflow.com/questions/16452277/how-can-i-extend-the-constructor-of-an-angularjs-resource-resource