编程语言
首页 > 编程语言> > JavaScript-$scope.$apply会降低性能

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

作者:互联网

我有一个使用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()的反跳调用.

标签:angularjs,angularjs-scope,signalr-client,asp-net,javascript
来源: https://codeday.me/bug/20191028/1952342.html