1

我正在尝试执行以下操作:

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

具有无限数量的可选参数。(广播“定义”:$broadcast(string, args...))

我想

eventService.emit =$rootScope.$broadcast;

会起作用,但不起作用($broadcast 函数可以访问 $rootscope 属性)和

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

似乎不起作用

谢谢您的帮助

原始代码:

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

    eventObject.emit = function(name){

       $rootScope.$broadcast(name);

    };
    return eventObject;
});
4

3 回答 3

6

你可以试试

eventService.emit = function(){

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

在这里,您正在使用参数“array”中的参数执行 $rootScope.$broadcast(它不是真正的数组,但行为类似),并在函数中使用 this(参数)作为 this。

于 2012-08-09T19:54:34.877 回答
1

您可以使用apply()此处的文档):

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

[1]:

于 2012-08-09T20:07:23.457 回答
0

当我想要很多选择时,我会这样做:

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

依此类推,我需要尽可能多的选项。

像这样称呼它:

myFunction({ whateverOptionYouWant: "some option variable" });
myFunction();
myFunction({ 
 whateverOptionYouWant: "some option variable", 
 whateverOTHEROptionYouWant: "some other variable"});
于 2012-08-09T19:54:42.687 回答