Home  >  Article  >  Web Front-end  >  [Translation] Angular property binding update mechanism - Laravel/Angular technology sharing

[Translation] Angular property binding update mechanism - Laravel/Angular technology sharing

寻∝梦
寻∝梦Original
2018-09-07 16:11:111294browse
This article mainly talks about the angularjs attribute binding update mechanism, as well as the detailed explanation of angularjs update attributes, all in this article. Now let us read this article together.

Explanation of angularjs attribute binding update mechanism:

All modern front-end frameworks use components to synthesize UI, which naturally results in a parent-child component hierarchy , which requires the framework to provide a mechanism for parent-child component communication. Similarly, Angular also provides two ways to implement parent-child component communication: Input and output binding and Shared service. For stateless presentational components I prefer the input and output binding approach, whereas for stateful container components I use the shared services approach.

This article mainly introduces the input and output binding methods, especially how Angular updates the input value of the child component when the input binding value of the parent component changes. If you want to know how Angular updates the current component DOM, you can check out Translated Angular DOM Update Mechanism. This article will also help deepen your understanding of this article. Since we will be exploring how Angular updates input binding properties of DOM elements and components, it is assumed that you know how Angular internally represents components and directives. If you don't know much and are interested, you can check out 译文Why Angular Internals No component found. This article mainly talks about how Angular uses directive form to represent components internally. This article uses the two concepts of components and instructions interchangeably, because Angular internally treats components as instructions.

Template binding syntax

You may know that Angular provides Property binding syntax —— [], this syntax is very common, it can Used on child components, but also on native DOM elements. If you want to pass data from the parent component to the child component b-comp or the native DOM element span, you can write this in the parent component template:

import { Component } from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'a-comp',
  template: `
      <b-comp [textContent]="AText"></b-comp>
      <span [textContent]="AText"></span>
  `
})
export class AComponent {
  AText = 'some';
}

You don't have to do any extra work for native DOM elements, but for child components b-comp you need to declare the input attribute textContent:

@Component({
    selector: 'b-comp',
    template: 'Comes from parent: {{textContent}}'
})
export class BComponent {
    @Input() textContent;
}

so that it acts as the parent component# When ##AComponent.AText properties change, Angular will automatically update the child component BComponent.textContent property, and the native element span.textContent property. At the same time, the life cycle hook function ngOnChanges of the sub-component BComponent will also be called (note: there is actually ngDoCheck, see below).

You may be curious how Angular knows that

BComponent and span support textContent binding. This is because when the Angular compiler parses the template, if it encounters a simple DOM element such as span, it will find out whether the element is defined in dom_element_schema_registry, thereby knowing that it is an HTMLElement subclass. textContent is one of the attributes (Note: You can try if span is bound to a [abc]=AText, an error will be reported and abc cannot be recognized. attribute); if you encounter a component or directive, check whether the metadata input attribute of its decorator @Component/@Directive contains the binding attribute item. If not, the compiler will also throw an error:

Can’t bind to ‘textContent’ since it isn’t a known property of …
This knowledge is easy to understand, now let us take a closer look at what is happening internally.

Component Factory

Although the input attributes are bound to the sub-component

BComponent and span elements, all the information required for the input binding update is In the component factory of the parent component AComponent. Let's take a look at the component factory code of AComponent:

function View_AComponent_0(_l) {
  return jit_viewDef1(0, [
     jit_elementDef_2(..., 'b-comp', ...),
     jit_directiveDef_5(..., jit_BComponent6, [], {
         textContent: [0, 'textContent']
     }, ...),
     jit_elementDef_2(..., 'span', [], [[8, 'textContent', 0]], ...)
  ], function (_ck, _v) {
     var _co = _v.component;
     var currVal_0 = _co.AText;
     var currVal_1 = 'd';
     _ck(_v, 1, 0, currVal_0, currVal_1);
  }, function (_ck, _v) {
     var _co = _v.component;
     var currVal_2 = _co.AText;
     _ck(_v, 2, 0, currVal_2);
  });
}
If you read

Translation Angular DOM update mechanism or Translation Why components are not found inside Angular, you will be more familiar with each view node in the above code. Among the first two nodes, jit_elementDef_2 is the element node, jit_directiveDef_5 is the instruction node, these two constitute the sub-component BComponent; the third node jit_elementDef_2 is also an element node, forming the span element. (If you want to learn more, go to the PHP Chinese website AngularJS Development Manual to learn)

Node Binding

Nodes of the same type use the same node definition function, but the differences The parameters received are different, for example

jit_directiveDef_5 The node definition function parameters are as follows:

jit_directiveDef_5(..., jit_BComponent6, [], {
    textContent: [0, 'textContent']
}, ...),
Among them, the parameter

{textContent: [0, 'textContent']} is called props, you can view the parameter list of the directiveDef function:

directiveDef(..., props?: {[name: string]: [number, string]}, ...)

props The parameter is an object, and each key is the binding attribute name. The corresponding value is an array composed of the binding index and the binding attribute name. For example, in this example there is only one binding, textContent The corresponding value is:

{textContent: [0, 'textContent']}
If the instruction has multiple bindings Definitely, for example:

<b-comp [textContent]="AText" [otherProp]="AProp">

props 参数值也包含两个属性:

jit_directiveDef5(49152, null, 0, jit_BComponent6, [], {
    textContent: [0, 'textContent'],
    otherProp: [1, 'otherProp']
}, null),

Angular 会使用这些值来生成当前指令节点的 binding,从而生成当前视图的指令节点。在变更检测时,每一个 binding 决定 Angular 使用哪种操作来更新节点和提供上下文信息,绑定类型是通过 BindingFlags 设置的(注:每一个绑定定义是 BindingDef,它的属性 flags: BindingFlags 决定 Angular 该采取什么操作,比如 Class 型绑定和 Style 型绑定都会调用对应的操作函数,见下文)。比如,如果是属性绑定,编译器会设置绑定标志位为:

export const enum BindingFlags {
    TypeProperty = 1 << 3,
注:上文说完了指令定义函数的参数,下面说说元素定义函数的参数。

本例中,因为 span 元素有属性绑定,编译器会设置绑定参数为 [[8, 'textContent', 0]]

jit_elementDef2(..., 'span', [], [[8, 'textContent', 0]], ...)

不同于指令节点,对元素节点来说,绑定参数结构是个二维数组,因为 span 元素只有一个绑定,所以它仅仅只有一个子数组。数组 [8, 'textContent', 0] 中第一个参数也同样是绑定标志位 BindingFlags,决定 Angular 应该采取什么类型操作(注:[8, 'textContent', 0] 中的 8 表示为 property 型绑定):

export const enum BindingFlags {
    TypeProperty = 1 << 3, // 8

其他类型标志位已经在文章 译 Angular DOM 更新机制 有所解释:

TypeElementAttribute = 1 << 0,
TypeElementClass = 1 << 1,
TypeElementStyle = 1 << 2,

编译器不会为指令定义提供绑定标志位,因为指令的绑定类型也只能是 BindingFlags.TypeProperty

注:节点绑定 这一节主要讲的是对于元素节点来说,每一个节点的 binding 类型是由 BindingFlags 决定的;对于指令节点来说,每一个节点的 binding 类型只能是 BindingFlags.TypeProperty

updateRenderer 和 updateDirectives

组件工厂代码里,编译器还为我们生成了两个函数:

function (_ck, _v) {
    var _co = _v.component;
    var currVal_0 = _co.AText;
    var currVal_1 = _co.AProp;
    _ck(_v, 1, 0, currVal_0, currVal_1);
},
function (_ck, _v) {
    var _co = _v.component;
    var currVal_2 = _co.AText;
    _ck(_v, 2, 0, currVal_2);
}

如果你读了 译 Angular DOM 更新机制,应该对第二个函数即 updateRenderer 有所熟悉。第一个函数叫做 updateDirectives。这两个函数都是 ViewUpdateFn 类型接口,两者都是视图定义的属性:

interface ViewDefinition {
  flags: ViewFlags;
  updateDirectives: ViewUpdateFn;
  updateRenderer: ViewUpdateFn;

有趣的是这两个函数的函数体基本相同,参数都是 _ck_v,并且两个函数的对应参数都指向同一个对象,所以为何需要两个函数?

因为在变更检测期间,这是不同阶段的两个不同行为:

  • 更新子组件的输入绑定属性

  • 更新当前组件的 DOM 元素

这两个操作是在变更检测的不同阶段执行,所以 Angular 需要两个独立的函数分别在对应的阶段调用:

  • updateDirectives——变更检测的开始阶段被调用,来更新子组件的输入绑定属性

  • updateRenderer——变更检测的中间阶段被调用,来更新当前组件的 DOM 元素

这两个函数都会在 Angular 每次的变更检测时 被调用,并且函数参数也是在这时被传入的。让我们看看函数内部做了哪些工作。

_ck 就是 check 的缩写,其实就是函数 prodCheckAndUpdateNode,另一个参数就是 组件视图数据。函数的主要功能就是从组件对象里拿到绑定属性的当前值,然后和视图数据对象、视图节点索引等一起传入 prodCheckAndUpdateNode 函数。其中,因为 Angular 会更新每一个视图的 DOM,所以需要传入当前视图的索引。如果我们有两个 span 和两个组件:

<b-comp [textContent]="AText"></b-comp>
<b-comp [textContent]="AText"></b-comp>
<span [textContent]="AText"></span>
<span [textContent]="AText"></span>

编译器生成的 updateRenderer 函数和 updateDirectives 函数如下:

function(_ck, _v) {
    var _co = _v.component;
    var currVal_0 = _co.AText;
    
    // update first component
    _ck(_v, 1, 0, currVal_0);
    var currVal_1 = _co.AText;
    
    // update second component
    _ck(_v, 3, 0, currVal_1);
}, 
function(_ck, _v) {
    var _co = _v.component;
    var currVal_2 = _co.AText;
    
    // update first span
    _ck(_v, 4, 0, currVal_2);
    var currVal_3 = _co.AText;

    // update second span
    _ck(_v, 5, 0, currVal_3);
}

没有什么更复杂的东西,这两个函数还不是重点,重点是 _ck 函数,接着往下看。

更新元素的属性

从上文我们知道,编译器生成的 updateRenderer 函数会在每一次变更检测被调用,用来更新 DOM 元素的属性,并且其参数 _ck 就是函数 prodCheckAndUpdateNode。对于 DOM 元素的更新,该函数经过一系列的函数调用后,最终会调用函数 checkAndUpdateElementValue,这个函数会检查绑定标志位是 [attr.name, class.name, style.some] 其中的哪一个,又或者是属性绑定:

case BindingFlags.TypeElementAttribute -> setElementAttribute
case BindingFlags.TypeElementClass     -> setElementClass
case BindingFlags.TypeElementStyle     -> setElementStyle
case BindingFlags.TypeProperty         -> setElementProperty;

上面代码就是刚刚说的几个绑定类型,当绑定标志位是 BindingFlags.TypeProperty,会调用函数 setElementProperty,该函数内部也是通过调用 DOM Renderer 的 setProperty 方法来更新 DOM。

注:setElementProperty 函数里这行代码 view.renderer.setProperty(renderNode,name, renderValue);,renderer 就是 Renderer2 interface,它仅仅是一个接口,在浏览器平台下,它的实现就是 DefaultDomRenderer2

更新指令的属性

上文中已经描述了 updateRenderer 函数是用来更新元素的属性,而 updateDirective 是用来更新子组件的输入绑定属性,并且变更检测期间传入的参数 _ck 就是函数 prodCheckAndUpdateNode。只是进过一系列函数调用后,最终调用的函数却是checkAndUpdateDirectiveInline,这是因为这次节点的标志位是 NodeFlags.TypeDirective

checkAndUpdateDirectiveInline 函数主要功能如下:

  1. 从当前视图节点里获取组件/指令对象

  2. 检查组件/指令对象的绑定属性值是否发生改变

  3. 如果属性发生改变:

    a. 如果变更策略设置为 OnPush,设置视图状态为 checksEnabled

    b. 更新子组件的绑定属性值

    c. 准备 SimpleChange 数据和更新视图的 oldValues 属性,新值替换旧值

    d. 调用生命周期钩子 ngOnChanges

  4. 如果该视图是首次执行变更检测,则调用生命周期钩子 ngOnInit

  5. 调用生命周期钩子 ngDoCheck

当然,只有在生命周期钩子在组件内定义了才被调用,Angular 使用 NodeDef 节点标志位来判断是否有生命周期钩子,如果查看源码你会发现类似如下代码:

if (... && (def.flags & NodeFlags.OnInit)) {
  directive.ngOnInit();
}
if (def.flags & NodeFlags.DoCheck) {
  directive.ngDoCheck();
}

和更新元素节点一样,更新指令时也同样把上一次的值存储在视图数据的属性 oldValues 里(注:即上面的 3.c 步骤)。

好了,本篇文章到这就结束了(想看更多就到PHP中文网AngularJS使用手册中学习),有问题的可以在下方留言提问。


The above is the detailed content of [Translation] Angular property binding update mechanism - Laravel/Angular technology sharing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn