简体   繁体   English

Angular 2 - 替换$ scope。$ apply?

[英]Angular 2 - Substitute for $scope.$apply?

$scope.$apply will no longer be part of Angular 2. Then how do we let Angular know to update the DOM if any of the bound properties have been changed outside the regular angular execution context? $scope.$apply将不再是Angular 2的一部分。那么如果在常规角度执行上下文之外更改了任何绑定属性,我们如何让Angular知道更新DOM?

Taken from a blog post by Minko Gechev : 摘自Minko Gechev的博客文章

No more $scope.$apply 没有更多$ scope。$ apply

But how then AngularJS knows that anything outside it's execution context has taken a place? 但是AngularJS怎么知道它的执行环境之外的任何东西都取而代之? Lets think where the changes might come from: 让我们思考一下变化的来源:

  • setTimeout 的setTimeout
  • setInterval 的setInterval
  • prompt (yeah, there are people who still use it…) 提示(是的,有人还在使用它......)
  • XMLHttpRequest XMLHttpRequest的
  • WebSockets 的WebSockets

  • ...

For which the answer is: 答案是:

在此输入图像描述

I understand that patching the browser built-in javascript functions to notify of any changes to Angular is something that can be done in a relatively safe manner (without introducing subtle bugs) and would be very convenient for the developer. 我知道修补浏览器内置的javascript函数来通知Angular的任何更改是可以以相对安全的方式完成的(不会引入细微的错误)并且对开发人员来说非常方便。 But what about third party APIs (such as jQuery.fadeIn ) or if the browser exposes some new asynchronous API which isn't covered? 但是第三方API(例如jQuery.fadeIn )或浏览器是否公开了一些未涵盖的新异步API呢? What's the substitute for old $scope.$apply ? 什么是旧的$scope.$apply的替代品$scope.$apply

  1. import NgZone from core 从核心导入NgZone
  2. private zone: NgZone in your constructor private zone: NgZone构造函数中的private zone: NgZone
  3. this.zone.run(() => {}); where you would normally scope.$apply 你通常会在哪里scope.$apply

or 要么

  1. ChangeDetectorRef
  2. private chRef: ChangeDetectorRef
  3. chRef.detectChanges();

So the library that does all this monkey patching is zone.js . 因此,执行所有这些猴子修补的库是zone.js。

jQuery.fadeIn calls setInterval , setInterval is monkey patched, as long as you called jQuery.fadeIn within a zone.run . jQuery.fadeIn调用setIntervalsetInterval是猴子打补丁,只要你叫jQuery.fadeIn一个内zone.run

zone.fork and zone.run kind of replace $scope.$apply , but it's different because it detects itself when asynchronous things have finished, whereas you have to call $scope.$apply manually when you know things have finished. zone.forkzone.run替换$scope.$apply ,但它不同,因为它在异步事件完成时检测到自己,而你必须调用$scope.$apply在你知道事情结束时手动 $scope.$apply See also this question+answer: Use zone.js to detect current execution context from anywhere? 另请参阅此问题+答案: 使用zone.js从任何地方检测当前执行上下文?

if the browser exposes some new asynchronous API which isn't covered? 如果浏览器公开了一些未涵盖的新异步API?

I guess they will patch that too. 我猜他们也会补丁。

If everything else fails , you can still call zone.afterTask() manually. 如果其他一切都失败了 ,您仍然可以手动调用zone.afterTask()
I guess that's what you were looking for :) 我猜这就是你要找的:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM