我有一个使用 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 theexpression
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 afterexpression
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/