javascript – 放置资源专用逻辑的位置

前端之家收集整理的这篇文章主要介绍了javascript – 放置资源专用逻辑的位置前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
你能帮助我,考虑在AngularJS中放置资源(服务)的业务逻辑.我觉得在我的资源上创建一些类似抽象的抽象应该是很棒的,但我不知道如何.

API调用

  1. > GET /customers/1
  2. < {"first_name": "John","last_name": "Doe","created_at": '1342915200'}

资源(CoffeScript):

  1. services = angular.module('billing.services',['ngResource'])
  2. services.factory('CustomerService',['$resource',($resource) ->
  3. $resource('http://virtualmaster.apiary.io/customers/:id',{},{
  4. all: {method: 'GET',params: {}},find: {method: 'GET',params: {},isArray: true}
  5. })
  6. ])

我想做一些像:

  1. c = CustomerService.get(1)
  2. c.full_name()
  3. => "John Doe"
  4.  
  5. c.months_since_creation()
  6. => '1 month'

非常感谢任何想法.
亚当

解决方法

需要在域对象实例上调用逻辑的最佳位置将是该域对象的原型.

你可以写一些这样的东西:

  1. services.factory('CustomerService',function($resource) {
  2.  
  3. var CustomerService = $resource('http://virtualmaster.apiary.io/customers/:id',{
  4. all: {
  5. method: 'GET',params: {}
  6. }
  7. //more custom resources methods go here....
  8. });
  9.  
  10. CustomerService.prototype.fullName = function(){
  11. return this.first_name + ' ' + this.last_name;
  12. };
  13.  
  14. //more prototype methods go here....
  15.  
  16. return CustomerService;
  17.  
  18. }]);

猜你在找的JavaScript相关文章