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

查看:32
本文介绍了Angular 2 - 替代 $scope.$apply?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$scope.$apply 将不再是 Angular 2 的一部分.那么如果任何绑定属性在常规 Angular 执行上下文之外发生了更改,我们如何让 Angular 知道更新 DOM?

摘自 .

jQuery.fadeIn 调用 setIntervalsetInterval 是猴子修补的,只要你调用了 jQuery.fadeInzone.run 中.

zone.forkzone.run 有点替代 $scope.$apply,但它不同,因为它在异步事物时检测自己已经完成,而当你知道事情已经完成时,你必须$scope.$apply手动调用.另请参阅此问题+答案:使用 zone.js从任何地方检测当前执行上下文?

<块引用>

如果浏览器公开了一些未涵盖的新异步 API?

我想他们也会修补它.

如果其他一切都失败了,您仍然可以手动调用 zone.afterTask().
我想这就是你要找的 :)

$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?

Taken from a blog post by Minko Gechev:

No more $scope.$apply

But how then AngularJS knows that anything outside it’s execution context has taken a place? Lets think where the changes might come from:

  • setTimeout
  • setInterval
  • prompt (yeah, there are people who still use it…)
  • XMLHttpRequest
  • 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. But what about third party APIs (such as jQuery.fadeIn) or if the browser exposes some new asynchronous API which isn't covered? What's the substitute for old $scope.$apply?

解决方案

So the library that does all this monkey patching is zone.js.

jQuery.fadeIn calls setInterval, setInterval is monkey patched, as long as you called jQuery.fadeIn within a 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. See also this question+answer: Use zone.js to detect current execution context from anywhere?

if the browser exposes some new asynchronous API which isn't covered?

I guess they will patch that too.

If everything else fails, you can still call zone.afterTask() manually.
I guess that's what you were looking for :)

这篇关于Angular 2 - 替代 $scope.$apply?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆