保持“$ watch”功能远离控制器的最佳做法 [英] Best practice in keeping `$watch` functions away from your controllers
问题描述
我试图找到一些关于将 $ watch
函数从控制器移动到工厂的最佳实践的好例子。例如。
I tried to find some good examples on best practice in moving $watch
functions from a controller to a factory, for example.
我发现的是,实际上对于什么是最好的做法没有一致意见。我已经看到了将 $ rootScope
注入工厂的示例以及 $ watch
,以便在那里进行值更改。
What I have found is that actually there isn't a unanimous opinion on what's best to do. I've seen examples of injection the $rootScope
into a factory and $watch
ing for value changes there.
另一个建议是尽可能避免使用它们,并在元素本身上使用 ngChange
,例如:
Another suggestion is to avoid them whenever possible, and to use ngChange
instead on the element itself, for example:
<div ng-model="foo.bar" ng-change="updateValue(foo.bar)"></div>
您建议的方式是什么?自从我开始学习AngularJS以来,我一直在我的控制器中放置 $ watch
es,但现在我想采用最佳实践方法,尝试制作并保持我的控制器像可能。
What is your proposed way? I've been putting $watch
es in my controllers ever since I started learning AngularJS but now I want to embrace best practice approaches, trying to make and keep my controllers as thin as possible.
推荐答案
我想放在哪里 $ watch
在很大程度上取决于用例场景。关于 $ watch
最重要的一点是不要在句柄功能中做任何艰苦的工作,特别是如果你正在观看的内容正在发生很大变化;这会严重阻碍你的表现。并确保在您的句柄功能中您不会更改已经被观看的其他内容,因为这将导致更改链更新。
I guess where to put $watch
heavily depends on the use-case scenario. The most important thing to be careful about $watch
is not to do any hard-work inside the handle function especially if what you are watching is changing a lot; that would highly damper your performance. And be sure that in your handle function you don't change something else which is already being watched as this will cause a chain of change updates.
如果您确定您正在观看的变量只能在一个地方更改,最好使用 ng-change
而不是 $ watch
因为你已经知道它被改变的地方。
If you are sure that the variable you are watching can only be changed from one place, it is better idea to use ng-change
rather than $watch
as you already know the place where it gets changed.
一般来说,最好不要填写 rootScope
使用不必要的对象,但是如果你正在观察整个应用程序中使用的某些变量,例如当前用户的属性,我想将 $ watch
表达式放入 $ rootScope
。
It is generally good practice not to fill rootScope
with unnecessary objects, but if you are watching for some variable which is used in entire application such as current user's attribute, I guess it would make sense to put $watch
expression into $rootScope
.
这篇关于保持“$ watch”功能远离控制器的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!