草庐IT

javascript - 为什么不建议将 $rootScope 与函数一起使用?

coder 2024-05-12 原文

在研究 Angularjs 的 FEQ 时,我看到了以下文章:

$rootScope exists, but it can be used for evil

Scopes in Angular form a hierarchy, prototypally inheriting from a root scope at the top of the tree. Usually this can be ignored, since most views have a controller, and therefore a scope, of their own.

Occasionally there are pieces of data that you want to make global to the whole app. For these, you can inject $rootScope and set values on it like any other scope. Since the scopes inherit from the root scope, these values will be available to the expressions attached to directives like ng-show just like values on your local $scope.

Of course, global state sucks and you should use $rootScope sparingly, like you would (hopefully) use with global variables in any language. In particular, don't use it for code, only data. If you're tempted to put a function on $rootScope, it's almost always better to put it in a service that can be injected where it's needed, and more easily tested.

Conversely, don't create a service whose only purpose in life is to store and return bits of data.

— AngularJS FAQ - $rootScope exists, but it can be used for evil

所以我的疑问是为什么不建议将 $rootScope 作为全局函数用于函数?有任何性能问题吗?

最佳答案

我过去已经回答过这个问题,但你问这些问题很好。

$rootScope exists, but it can be used for evil Scopes in Angular form a hierarchy, prototypally inheriting from a root scope at the top of the tree. Usually this can be ignored, since most views have a controller, and therefore a scope, of their own.

非隔离范围是分层的,但大多数开发人员应该使用具有隔离范围的指令。 AngularJS 作用域的层次结构本质是 Angular 应用程序中许多错误的来源。这是一个我喜欢称之为作用域出血的问题,其中作用域属性在 DOM 树中的某处被神奇地修改,而你不知道为什么。

Angular 的默认 行为是针对固有范围的,这使得一个 Controller 很容易更新另一个 Controller 管理的内容,依此类推。这就是在源代码之间创建意大利面条式连接的方式。使维护该代码变得非常困难。

Occasionally there are pieces of data that you want to make global to the whole app. For these, you can inject $rootScope and set values on it like any other scope.

不,那是不正确的。 AngularJS 允许您定义常量、值和服务等内容。这些是可以注入(inject)到路由、 Controller 和指令中的东西。这就是你如何让你的应用程序全局访问的东西,如果你想让你的 Controller 或指令可测试,你也可以这样做。单元测试编写者不知道指令或 Controller 所依赖的 $rootScope 中应该有哪些属性。他们必须假设 $rootScope 没有发生变化以提供服务或数据。

Of course, global state sucks and you should use $rootScope sparingly, like you would (hopefully) use with global variables in any language.

问题不是 $rootScope,而是人们用它做什么。许多应用程序将当前用户、身份验证 token 和 session 数据添加到 rootScope 中。这最终会在模板中大量使用(如果用户登录则显示 X,否则显示 Y)。问题是 HTML 不传达范围层次结构。因此,当您看到 {{user.firstname + ' ' + user.lastname}} 时,您不知道变量 user 是从哪里来的。第二个问题是子作用域可以隐藏根属性。与前面的示例一样,如果指令执行此 scope.user = 'bla bla bla'。它没有替换 rootScope 上的值。它隐藏了它。现在您在模板中得到了一些奇怪的意想不到的东西,并且您不知道为什么变量 user 发生了变化。

Conversely, don't create a service whose only purpose in life is to store and return bits of data.

Angular 的 $cacheFactory$templateCache 是仅用于存储数据的服务示例。我认为作者试图鼓励在 Angular 的模块中使用常量和值,但这并不是一个好的描述。

So My doubt is why $rootScope is not recommended for functions as a global function? Is there any performance issue?

$rootScope 是angular.config(..) 期间唯一可用的范围。如果这是唯一一次您可以执行此操作,则在此期间可以修改范围。例如;您可能需要在应用程序启动之前注入(inject) API key 或 Google anayltics 变量。

任何 作用域上的函数通常不是一个好主意。主要是因为作用域中的所有内容都在模板的表达式中被消化。函数倾向于隐藏 繁重的操作。在调用函数时通过读取 HTML 无法判断模板的重量。我见过像 getHeight() 这样的范围函数,其中函数本身执行 3 级嵌套循环。每次 Angular 消化观察者以查看它是否已更改时,都必须调用该函数。您应该尽量让您的模板保持干燥

关于javascript - 为什么不建议将 $rootScope 与函数一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32761540/

有关javascript - 为什么不建议将 $rootScope 与函数一起使用?的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  3. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  4. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  5. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  6. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  7. ruby - ruby 中的 TOPLEVEL_BINDING 是什么? - 2

    它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput

  8. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  9. ruby - Infinity 和 NaN 的类型是什么? - 2

    我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串

  10. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

随机推荐