Skip to content

Commit 026e9c3

Browse files
committed
Add doc on reactivity, previously observables and state, and add in content binding docs in the html templates in 2.x docs
1 parent ea296df commit 026e9c3

2 files changed

Lines changed: 253 additions & 0 deletions

File tree

Lines changed: 224 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,224 @@
1+
---
2+
id: reactivity
3+
title: Reactivity
4+
layout: 2x
5+
eleventyNavigation:
6+
key: reactivity2x
7+
parent: advanced2x
8+
title: Reactivity
9+
navigationOptions:
10+
activeKey: reactivity2x
11+
description: Advanced observable features including access tracking, observation, arrays, and volatile properties.
12+
keywords:
13+
- observables
14+
- state
15+
- reactivity
16+
- arrays
17+
- volatile
18+
---
19+
20+
# Reactivity
21+
22+
The arrow function bindings and directives used in templates allow the `fast-element` templating engine to intelligently react by only updating the parts of the DOM that actually change, with no need for a virtual DOM, VDOM diffing, or DOM reconciliation algorithms. This approach enables top-tier initial render time, industry-leading incremental DOM updates, and ultra-low memory allocation.
23+
24+
When a binding is used within a template, the underlying engine uses a technique to capture which properties are accessed in that expression. With the list of properties captured, it then subscribes to changes in their values. Any time a value changes, a task is scheduled on the DOM update queue. When the queue is processed, all updates run as a batch, updating precisely the aspects of the DOM that have changed.
25+
26+
## Observables
27+
28+
To enable binding tracking and change notification, properties must be decorated with either `@attr` or `@observable`. Use `@attr` for primitive properties (string, bool, number) that are intended to be surfaced on your element as HTML attributes. Use `@observable` for all other properties. In addition to observing properties, the templating system can also observe arrays. The `repeat` directive is able to efficiently respond to array change records, updating the DOM based on changes in the collection.
29+
30+
These decorators are a means of meta-programming the properties on your class, such that they include all the implementation needed to support state tracking, observation, and reactivity. You can access any property within your template, but if it hasn't been decorated with one of these two decorators, its value will not update after the initial render.
31+
32+
:::important
33+
The `@attr` decorator can only be used in a `FASTElement` but the `@observable` decorator can be used in any class.
34+
:::
35+
36+
:::important
37+
Properties with only a getter, that function as a computed property over other observables, should not be decorated with `@attr` or `@observable`. However, they may need to be decorated with `@volatile`, depending on the internal logic.
38+
:::
39+
40+
## Observable Features
41+
42+
### Access tracking
43+
44+
When `@attr` and `@observable` decorated properties are accessed during template rendering, they are tracked, allowing the engine to deeply understand the relationship between your model and view. These decorators serves to meta-program the property for you, injecting code to enable the observation system. However, if you do not like this approach, for `@observable`, you can always implement notification manually. Here's what that would look like:
45+
46+
**Example: Manual Observer Implementation**
47+
48+
```ts
49+
import { Observable } from '@microsoft/fast-element';
50+
51+
export class Person {
52+
private _firstName: string;
53+
private _lastName: string;
54+
55+
get firstName() {
56+
Observable.track(this, 'firstName');
57+
return this._firstName;
58+
}
59+
60+
set firstName(value: string) {
61+
this._firstName = value;
62+
Observable.notify(this, 'firstName');
63+
}
64+
65+
get lastName() {
66+
Observable.track(this, 'lastName');
67+
return this._lastName;
68+
}
69+
70+
set lastName(value: string) {
71+
this._lastName = value;
72+
Observable.notify(this, 'lastName');
73+
}
74+
75+
get fullName() {
76+
return `${this.firstName} ${this.lastName}`;
77+
}
78+
}
79+
```
80+
81+
Notice that the `fullName` property does not need any special code, since it's computing based on properties that are already observable. There is one special exception to this: if you have a computed property with branching code paths, such as ternary operators, if/else conditions, etc, then you must tell the observation system that your computed property has *volatile* dependencies. In other words, which properties need to be observed may change from invocation to invocation based on which code path executes.
82+
83+
Here's how you would do that with a decorator:
84+
85+
```ts
86+
import { observable, volatile } from '@microsoft/fast-element';
87+
88+
export class MyClass {
89+
@observable someBoolean = false;
90+
@observable valueA = 0;
91+
@observable valueB = 42;
92+
93+
@volatile
94+
get computedValue() {
95+
return this.someBoolean ? this.valueA : this.valueB;
96+
}
97+
}
98+
```
99+
100+
Here's how you would do it without a decorator:
101+
102+
```ts
103+
import { Observable, observable } from '@microsoft/fast-element';
104+
105+
export class MyClass {
106+
@observable someBoolean = false;
107+
@observable valueA = 0;
108+
@observable valueB = 42;
109+
110+
get computedValue() {
111+
Observable.trackVolatile();
112+
return this.someBoolean ? this.valueA : this.valueB;
113+
}
114+
}
115+
```
116+
117+
### Internal observation
118+
119+
On the class where the `@attr` or `@observable` is defined, you can optionally implement a *propertyName*Changed method to easily respond to changes in your own state.
120+
121+
**Example: Property Change Callbacks**
122+
123+
```ts
124+
import { observable } from '@microsoft/fast-element';
125+
126+
export class Person {
127+
@observable name: string;
128+
129+
nameChanged(oldValue: string, newValue: string) {
130+
131+
}
132+
}
133+
```
134+
135+
### External observation
136+
137+
Decorated properties can be subscribed to, to receive notification of changes in the property value. The templating engine uses this, but you can also directly subscribe. Here's how you would subscribe to changes in the `name` property of a `Person` class:
138+
139+
**Example: Subscribing to an Observable**
140+
141+
```ts
142+
import { Observable } from '@microsoft/fast-element';
143+
144+
const person = new Person();
145+
const notifier = Observable.getNotifier(person);
146+
const handler = {
147+
handleChange(source: any, propertyName: string) {
148+
// respond to the change here
149+
// source will be the person instance
150+
// propertyName will be "name"
151+
}
152+
};
153+
154+
notifier.subscribe(handler, 'firstName')
155+
notifier.unsubscribe(handler, 'lastName');
156+
```
157+
158+
## Observing Arrays
159+
160+
So far, we've only seen how to observe properties on objects, but it's also possible to observe arrays for changes. Given an instance of an array, it can be observed like this:
161+
162+
**Example: Observing an Array**
163+
164+
```ts
165+
const arr = [];
166+
const notifier = Observable.getNotifier(arr);
167+
const handler = {
168+
handleChange(source: any, splices: Splice[]) {
169+
// respond to the change here
170+
// source will be the array instance
171+
// splices will be an array of change records
172+
// describing the mutations in the array in
173+
// terms of splice operations
174+
}
175+
};
176+
177+
notifier.subscribe(handler);
178+
```
179+
180+
There are a couple of important details to note with array observation:
181+
182+
* The `fast-element` library's ability to observe arrays is opt-in, in order that the functionality remain tree-shakeable. If you use a `repeat` directive anywhere in your code, you will be automatically opted in. However, if you wish to use the above APIs and are not using `repeat`, you will need to enable array observation by importing and calling the `enableArrayObservation()` function.
183+
* The observation system cannot track changes made directly through an index update. e.g. `arr[3] = 'new value';`. This is due to a limitation in JavaScript. To work around this, update arrays with the equivalent `splice` code e.g. `arr.splice(3, 1, 'new value');`
184+
* If the array is a property of an object, you will often want to observe both the property and the array. Observing the property will allow you to detect when the array instance is completely replaced on the object, while observing the array will allow you to detect changes in the array instance itself. When the property changes, be sure to unsubscribe to the old array and set up a subscription to the new array instance.
185+
* Observing an array only notifies on changes to the array itself. It does not notify on changes to properties on objects held within the array. Separate observers would need to be set up for those individual properties. These could be set up and torn down in response to changes in the array though.
186+
187+
## Observing Volatile Properties
188+
189+
In addition to watching properties and arrays, you can also watch volatile properties.
190+
191+
**Example: Subscribing to a Volatile Property**
192+
193+
```ts
194+
import { Observable, defaultExecutionContext } from '@microsoft/fast-element';
195+
196+
const myObject = new MyClass();
197+
const handler = {
198+
handleChange(source: any) {
199+
// respond to the change here
200+
// the source is the volatile binding itself
201+
}
202+
};
203+
const bindingObserver = Observable.binding(myObject.computedValue, handler);
204+
bindingObserver.observe(myObject, defaultExecutionContext);
205+
206+
// Call this to dismantle the observer
207+
bindingObserver.disconnect();
208+
```
209+
210+
### Records
211+
212+
To inspect which observable objects and properties were accessed from a `BindingObserver`, you can get the observation records from `BindingObserver.records()` after observing the binding.
213+
214+
**Example: Getting observation records**
215+
```ts
216+
const binding = (x: MyClass) => x.someBoolean ? x.valueA : x.valueB;
217+
const bindingObserver = Observable.binding(binding);
218+
const value = bindingObserver.observe({}, defaultExecutionContext);
219+
220+
for (const record of bindingObserver.records()) {
221+
// Do something with the binding's observable dependencies
222+
console.log(record.propertySource, record.propertyName)
223+
}
224+
```

sites/website/src/docs/2.x/getting-started/html-templates.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,35 @@ NameTag.define({
5252

5353
When the greeting attribute is updated, so will the template.
5454

55+
### Content
56+
57+
To bind the content of an element, simply provide the expression within the start and end tags of the element. It can be the sole content of the element or interwoven with other elements and text.
58+
59+
**Example: Basic Text Content**
60+
61+
```html
62+
<h3>${x => x.greeting.toUpperCase()}</h3>
63+
```
64+
65+
**Example: Interpolated Text Content**
66+
67+
```html
68+
<h3>${x => x.greeting}, my name is ${x => x.name}.</h3>
69+
```
70+
71+
**Example: Heterogeneous Content**
72+
73+
```html
74+
<h3>
75+
${x => x.greeting}, my name is
76+
<span class="name">${x => x.name}</span>.
77+
</h3>
78+
```
79+
80+
:::note
81+
Dynamic content is set via the `textContent` HTML property for security reasons. You *cannot* set HTML content this way. See the Properties binding section for the explicit, opt-in mechanism for setting HTML via `:innerHTML`.
82+
:::
83+
5584
### Booleans
5685

5786
Boolean bindings use the `?` symbol, use these for Boolean attributes.

0 commit comments

Comments
 (0)