2016-04-18 22 views
0

我得到这个事件:通功能,以角事件处理rootScope.on

app.run(function($rootScope){ 

document.addEventListener('keyup',function(){ 
if (e.keyCode ===13){ 
$rootScope.$broadcast("EnterPressed",e.target); 
} 

}) 

}) 

我想在我的控制器此命令触发事件:

$scope.$on('EnterPressed',console.log("pressed enter"); 

如果我运行上面的代码,当分页刷新我可以看到控制台上的“按下回车”消息

但是当我做它像这样:

$scope.$on('EnterPressed',function(){console.log("pressed enter")}; 

只有在按下回车键后,代码才会运行。

有什么区别?

回答

0

$scope.$on期望作为第二个参数的函数指针,如果你写了console.log("pressed enter")->那么这不是一个函数指针。这已经是一个函数调用。

$scope.$on('EnterPressed',console.log("pressed enter")); 

此时console.log("pressed enter")已经处理以计算该参数值(这里未定义)。

你的第二个例子是让此事件

$scope.$on('EnterPressed',function(){console.log("pressed enter")}; 

因为你只是用一个函数指针作为参数的正确途径。

+0

谢谢!它帮助我 –

+0

所以选择你的赢家;) – rootatdarkstar

0

第一种情况发生是因为表达式console.log("pressed enter")在页面加载时评估过一次。

带有任何参数的函数console.log返回undefined。所以$scope.$on('EnterPressed',console.log("pressed enter"));相当于$scope.$on('EnterPressed',undefined);,带有打印"pressed enter"到控制台的副作用。

在第二种情况下,您将回调函数传递给console.log,并且此函数仍未调用。当事件被呼叫$scope.$on调用传递函数。

要理解这一点,你必须看到这两个表达式之间的区别:

// passed the function: 
$scope.$on('EnterPressed', function(){ console.log("pressed enter") }); 

// passed result of the function: 
$scope.$on('EnterPressed', function(){ console.log("pressed enter") }()); 
+0

谢谢!它对我也有帮助:) –