javascript - $scope.$apply 会降低性能

标签 javascript asp.net angularjs angularjs-scope signalr.client

我有一个使用 AngularJS 的单页应用程序,我在其中遇到了一个性能问题。我的应用程序处理来自服务器端的传入事件,这些事件使用 ASP.NET SignalR 传递到客户端的 AngularJS 框架。我的应用程序可以接收数百万个事件,服务器端没有性能问题,它很容易将这些事件一个接一个地传递给 AngularJS 框架。问题出在客户端。处理事件后,我使用 $scope.$apply() 更新页面并显示事件。在这种情况下,一个接一个地接收到多个事件,每次调用 $scope.$apply() 都会减慢应用程序的速度并且不会快速显示事件。事件将随机传递,所以我什至不知道我的应用程序在任何时间点将如何接收任何事件。

有关如何解决此问题的任何想法都将非常有帮助。

谢谢。

最佳答案

而不是使用 $scope.$apply() , 使用 $scope.$evalAsync() 相反。

来自文档:

Executes the expression on the current scope at a later point in time.

The $evalAsync makes no guarantees as to when the expression will be executed, only that:

  • it will execute after the function that scheduled the evaluation (preferably before DOM rendering).
  • at least one $digest cycle will be performed after expression execution.

Any exceptions from the execution of the expression are forwarded to the $exceptionHandler service.

Note: if this function is called outside of a $digest cycle, a new $digest cycle will be scheduled. However, it is encouraged to always call code that changes the model from within an $apply call. That includes code evaluated via $evalAsync.

我也倾向于 $scope.$safeApply()方法也是对 $scope.$evalAsync() 的有效去抖调用.

关于javascript - $scope.$apply 会降低性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29816538/

相关文章:

c# - 连接到 wcf 管道

javascript - Angularjs CMS 的 url 中的 GET 请求

javascript - 关联元素并使正确的元素在按钮单击时出现的简单方法

javascript - 绑定(bind) html 时不会发生 knockout 表单提交

javascript - 一个 php 页面中的两个搜索栏

javascript - 在 JavaScript 中,如何在新的浏览器窗口中打开页面并滚动到特定位置?

c# - 在 ELMAH 获取异常之前捕获异常并清除它

c# - 中继器内动态控件的 View 状态问题

javascript - 是否可以在 Angular 日期范围选择器中设置动态范围?

javascript - ng-click 不适用于我的任何 div