0

I am building a node/angular app. And I am not used to javascript. I made a service for all my static list obects. I am trying to make this code as generic as possible. I think I can improve it more. Here is what I have for the moment (I put only 2, but I will have many more):

function returnSolList (n, $resource) {
    return $resource(n+'/', {}, {'query' : {method : 'GET', cache : true, isArray:true } });
}

mod.factory('Cities', ['$resource', function($resource) {return returnSolList('cities', $resource);}]);
mod.factory('Boites', ['$resource', function($resource) {return returnSolList('boites', $resource);}]);

I think I could do better with something maybe by declaring my services in a list ['Cities', 'Boites'] and then loop to build the factory. Also there is redundance in the $resource that I would like to get rid of.

But I am not sure how to do it.

Tyvain
  • 2,640
  • 6
  • 36
  • 70

1 Answers1

2

You can add 'cities', 'boites',... in an array and use a for to generate the code, but it will be a little complex. Do u really want that?

function returnSolList (n, $resource) {
    return $resource(n+'/', {}, {'query' : {method : 'GET', cache : true, isArray:true } });
}

var names = ['Cities','Boites'];
for(var i=0; i<names.length; i++){
    mod.factory(
        names[i],
        [
            '$resource',
            (function(name){
                return function($resource){
                    return returnSolList(name, $resource);
                }
            })(names[i].toLowerCase())
        ]
    );
}

The complex part is that you need to return a function which is using a variable that uses i inside the for while i is changing. You need to pass i into a function so it will be saved local (on the scope).


More about javascript closures : How do JavaScript closures work?

For javascript code minify/speedup check Closure Compiler

GramThanos
  • 3,572
  • 1
  • 22
  • 34
  • The solution I have know work well, and the code is simple. I thought I could make it even more simple with a loop. But as I can see it's quite complicated. I will keep my code as it is. Thank for the answer and for the link. – Tyvain Jun 06 '14 at 00:17
  • I agree with you. Usually a loop makes things simpler, but when you have to declare functions inside loops the code is a little more complex and people get confused. The Closure Compiler is really good for debugging too. But be sure not to have warnings when you use it on big files. And if you are familiar with terminals, it also have a jar version. – GramThanos Jun 06 '14 at 05:27