Angular JS $ watch vs $ on [英] Angular JS $watch vs $on

查看:100
本文介绍了Angular JS $ watch vs $ on的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



实现此目的的明显方法是使用事件广播( $ broadcast )和听众( $ on )。



如果使用$手表是事件广播的替代品,我很好奇。如果是这样,两个比较如何?



据我所知,每个$ digest循环都要评估待观察的表达式。
事件比观看更有效吗?

解决方案

$ watch 函数用于监视作用域上的变量。范围继承允许您同时观看父范围变量,这绝对是您的用例的方式。
正如你所说, $ on 用于观看事件,您可以将 $ broadcast 子范围或 $ emit 到父范围。这可以让你更多的控制,但是在编码时可能会导致更多的错误,因为您可以从不监视的点获取更新范围变量,并忘记通知侦听器。



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



由于指令获取范围它是(或从它继承),我会说 $ watch 是一个更清洁的选项。



如果你想在你的指令中有一个孤立的范围,你可以传递参数作为属性,并且 $观察他们。


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).

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

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

解决方案

The $watch function 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, $on is used to watch for events, which you can $broadcast to child scopes or $emit to 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.

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 $watch is a much cleaner option here.

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

这篇关于Angular JS $ watch vs $ on的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆