Code reuse

42 views
Skip to first unread message

César Costa

unread,
Sep 29, 2014, 9:10:30 AM9/29/14
to ang...@googlegroups.com
Hello,


I am have the this doubt: In my app model layer, i am duplicating a lot of code for common requests to api. How can i reuse my code to eliminate this common requests, like find, findAll etc.

I implemented a little plunk to show the problem. 


Thanks

James Cooke

unread,
Sep 29, 2014, 11:17:57 AM9/29/14
to ang...@googlegroups.com
Is it the parts like this that you don't like?
  $scope.findUsers = function() {
    User.findAll();  
  }

This can be simplified to:
$scope.findUsers = User.findAll();

You can do
$scope.userFactory = User;

This means you only have to assign a few things to the view however your view then has access to all of the User factory methods. If you don't like that perhaps you can wrap up the find users functionality into a directive? You don't have to assign anything to the view that way and the factories are singletons so any changes in the User factory will be available in your controllers and elsewhere too.

César Barone

unread,
Sep 29, 2014, 12:59:26 PM9/29/14
to ang...@googlegroups.com
Hi James, thanks for your response.

The exact part that i don't like is to repeat this code twice:

Company factory:
    findAll: function() {
      MyResource.doGET('companies');  
    }

User factory: 
    findAll: function() {
      MyResource.doGET('users');  
    }  


I'm searching for  a implementation that is similar to rails active record implementation, when i only extend ActiveModel and the common methods comes as bonus.

Thanks :)
 

--
You received this message because you are subscribed to a topic in the Google Groups "AngularJS" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/angular/63eLt6Kt_xE/unsubscribe.
To unsubscribe from this group and all its topics, send an email to angular+u...@googlegroups.com.
To post to this group, send email to ang...@googlegroups.com.
Visit this group at http://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.

James Cooke

unread,
Sep 29, 2014, 3:16:24 PM9/29/14
to ang...@googlegroups.com
I think what you are looking for is plain old prototypal inheritance. Create a function with your base functionality with the service eg

This is a very basic example but with a little modification it should work for you.

function resourceHandler(MyResource, type) {
  this.MyResource = MyResource;
  this.type = type;
}
resourceHandler.prototype.getBaseFunctions = function() {
  return {
    findAll: function() {
      this.MyResource.doGET(this.type);  
    } 
  };
}

app.factory('User', function(MyResource){
  var handler = new resourceHandler(MyResource, 'users');
  return handler.getBaseFunctions();
});
Reply all
Reply to author
Forward
0 new messages