污染$ scope对象是否会影响性能?

编程入门 行业动态 更新时间:2024-10-11 23:26:47
本文介绍了污染$ scope对象是否会影响性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个控制器,其中$ scope对象用于存储仅在同一控制器内本地使用的方法和值.有很多这样的事情:

I have a controller where the $scope object has been used to store methods and values that are only used locally within the same controller. There is a lot of this going on:

$scope.foo = 'something'; $scope.bar = 'something else';

...等等.这些值均未在视图中使用.我的问题是污染$ scope对象是否会影响性能?清理掉这个好主意,使$ scope对象中只包含视图所需的值和方法吗?

... and so on. None of these values are used within the view. My question is does polluting the $scope object affect performance? Is it a good idea to clean this up so only values and methods needed for the view are contained in the $scope object?

推荐答案

是的,污染$scope确实会影响性能,但是取决于您的范围有多个观察者,这些观察者经常变化,然后会产生更多的间接费用.请参考 此答案 ,其中涵盖了同一点

Yes, Polluting $scope does affect performance, but its depends your scope has multiple watchers which are frequently changing then that will create a more overhead cost. Refer this answer which has covered same point

为避免这种情况,建议您对代码进行良好的重构

For avoiding this situation I'd suggest you to do good re-factoring of code

在需要时处理控制器中的所有逻辑,否则请通过充分利用每个组件来分离逻辑.

Handle all the logic in controller whenever required otherwise do separate a logic by making good use of each component.

  • 将通用方法(逻辑)移动到在多个地方使用的service/factory/provider,以便可以共享.
  • 如果某个值是固定的,则它们不会改变,然后将其移至constant/value
  • 每当您觉得需要保留在$scope中的逻辑相同时,它就会自行将该逻辑移至通用控制器.必要时,您可以使用$controller注入器
  • 注入当前的控制器范围
  • Move common method(logic) to service/factory/provider which is used in multiple place, so that it would be sharable.
  • If some value are fixed, they are not gonna change then move them to constant/value
  • Whenever you feel like you have same logic which needs to be keep in $scope it self then move that logic to common controller. When required you could inject in your current controller scope using $controller injector
  • 还请参考 了解范围 清楚了解范围的使用

    Also refer Understanding Of Scope for clear understanding of use of scope

    更多推荐

    污染$ scope对象是否会影响性能?

    本文发布于:2023-10-18 15:48:11,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1504663.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:是否会   对象   性能   scope

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!