大佬教程收集整理的这篇文章主要介绍了如何扩展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);
以上是大佬教程为你收集整理的如何扩展AngularJS资源($资源)的构造函数?全部内容,希望文章能够帮你解决如何扩展AngularJS资源($资源)的构造函数?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。