javascript Angular JS $watch 与 $on

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23561302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:06:06  来源:igfitidea点击:

Angular JS $watch vs $on

javascriptangularjseventslistenerwatch

提问by Yogesh Mangaj

I want to execute a function inside a directive, whenever there is a state change in the parent scope.

每当父作用域中的状态发生变化时,我都想在指令中执行一个函数。

The obvious way to achieve this is to use event broadcasts ($broadcast) and listeners ($on).

实现这一点的显而易见的方法是使用事件广播 ( $broadcast) 和侦听器 ( $on)。

I am curious if using a $watch is an alternative to event broadcast. If it is, how do the two compare?

我很好奇使用 $watch 是否可以替代事件广播。如果是,两者如何比较?

As far as I understand, the expression to be watched is evaluated every $digest cycle. So are events more efficient than watch?

据我了解,每个 $digest 循环都会对要观察的表达式进行评估。那么事件是否比观看更有效?

采纳答案by Ferdinand Torggler

The $watchfunction is used to watch variables on the scope. Scope inheritance allows you to watch parent scope variables as well, so that is definitely the way to go for your use case. As you correctly said, $onis used to watch for events, which you can $broadcastto child scopes or $emitto parent scopes. This gives you much more control, but it might cause more mistakes while coding, since you could get an update to a scope variable from a point which you don't monitor and forget to notify the listeners.

$watch函数用于观察作用域上的变量。作用域继承也允许您观察父作用域变量,因此这绝对是您的用例的方法。正如您所说的那样,$on用于监视事件,您可以$broadcast将其用于子作用域或$emit父作用域。这给了你更多的控制,但它可能会在编码时导致更多的错误,因为你可以从一个你没有监视的点更新范围变量并忘记通知侦听器。

You can still use events when you don't inherit scope variables. But be careful not to pollute a large scope, using services might be an option there, because you immediately see whether it is injected or not.

当您不继承范围变量时,您仍然可以使用事件。但是要注意不要污染大范围,在那里使用服务可能是一种选择,因为您可以立即看到它是否被注入。

Since a directive gets the scope it is on (or inherits from it), I would say $watchis a much cleaner option here.

由于指令获得它所在的范围(或从它继承),我会说$watch这里是一个更清晰的选择。

If you want to have an isolated scope on your directive, you can pass arguments as attributes and $observethem.

如果你想在你的指令上有一个独立的作用域,你可以将参数作为属性和$observe它们传递。