cricardol
cricardol

Reputation: 4222

Optional arguments javascript trick

I'm trying to do the following:

eventService.emit = function(name, optionalArg1, optionalArg2,... ){
    $rootScope.$broadcast(name, optionalArg1, optionalArg2,...);
};

with an unlimited number of optional arguments. (broadcast "definition": $broadcast(string, args...))

I thought

eventService.emit =$rootScope.$broadcast;

would work but it doesn't($broadcast function may access to $rootscope attributes) and

eventService.emit = function(){
    $rootScope.$broadcast(arguments);
};

doesn't seem to work

Thanks for the help

original code:

services.factory('eventService', function($rootScope, $http){
    var eventObject = {};

    eventObject.emit = function(name){

       $rootScope.$broadcast(name);

    };
    return eventObject;
});

Upvotes: 1

Views: 546

Answers (3)

nicosantangelo
nicosantangelo

Reputation: 13716

You could try

eventService.emit = function(){

    $rootScope.$broadcast.apply($rootScope, arguments); //you can change "this" to whatever you need
};

Here you are executing $rootScope.$broadcast with the parameters in the arguments "array" (it's not really an array but behaves like one), and using this (the parameter) as this in the function.

Upvotes: 6

Wolfgang Stengel
Wolfgang Stengel

Reputation: 2856

You could use apply() (documentation here):

eventService.emit = function(name, optionalArg1, optionalArg2,... )
{
    $rootScope.$broadcast.apply(this, arguments);
};

[1]:

Upvotes: 1

Travis J
Travis J

Reputation: 82267

What I do when I want a lot of options is this:

function myFunction(options){
 if( options["whateverOptionYouWant"] != undefined ){
  //TODO: implement whatever option you want
 }
 if( options["whateverOTHEROptionYouWant"] != undefined ){
  //TODO: implement whatever OTHER option you want
 }
}

and so on for as many options as I need.

Call it like this:

myFunction({ whateverOptionYouWant: "some option variable" });
myFunction();
myFunction({ 
 whateverOptionYouWant: "some option variable", 
 whateverOTHEROptionYouWant: "some other variable"});

Upvotes: 0

Related Questions