[DOC] doc: add observer doc

This commit is contained in:
Géry Debongnie
2019-04-25 15:28:20 +02:00
parent 40613e0a76
commit f23a26426d
2 changed files with 57 additions and 1 deletions
+8
View File
@@ -28,6 +28,11 @@ OWL components are the building blocks for user interface. They are designed to
OWL components are defined as a subclass of Component. The rendering is
exclusively done by a [QWeb](qweb.md) template (either defined inline or preloaded in QWeb).
The rendering is done by QWeb, which will generate a virtual dom representation
of the widget, then patch the DOM to apply the changes in an efficient way.
OWL components observe their states, and rerender themselves whenever it is
changed. This is done by an [observer](observer.md).
## Example
@@ -106,6 +111,9 @@ will be used to render the component template.
that this should be very rare to have to do it manually, the Owl framework is
most of the time responsible for doing that at an appropriate moment.
Note that the render method is asynchronous, so one cannot observe the updated
DOM in the same stack frame.
- **`shouldUpdate(nextProps)`**: this method is called each time a component's props
are updated. It returns a boolean, which indicates if the widget should
ignore a props update. If it returns false, then `willUpdateProps` will not
+49 -1
View File
@@ -1,6 +1,54 @@
# 🦉 Observer 🦉
Owl need to be able to react to state changes. For example, whenever the state
of a component is changed, we need to rerender it. To help with that, we have
an Observer class. Its job is to observe some object state, and react to any
change. To do that, it recursively replace all keys of the observed state by
getters and setters.
For example, this code will display `update` in the console:
```javascript
const observer = new owl.Observer();
observer.notifyCB = () => console.log("update");
observer.observe(obj);
const obj = { a: { b: 1 } };
obj.a.b = 2;
```
## Technical Limitations
Cannot observe new keys => need to use special method.
Since the observer uses getters and setters, it is actually unable to react to
changes in two situations:
- adding a key to an object:
```javascript
const observer = new owl.Observer();
const obj = { a: 1 };
observer.observe(obj);
obj.b = 2; // will do nothing
```
In that case, we need a way to tell the observer that something happened.
This can be done by using the `set` method:
```javascript
observer.set(obj, "b", 2);
```
- modifying an array by setting a new value at a given index:
```javascript
const observer = new owl.Observer();
const obj = { todos: [{ id: 1, text: "todo" }] };
observer.observe(obj);
obj[0] = { id: 2, text: "othertodo" }; // will do nothing, and obj[0] is not observed
```
In that case, the solution is the same, we can simply use the `set` method:
```javascript
observer.set(obj, 0, { id: 2, text: "othertodo" });
```