imp: work on store, refactor, improve todoapp

This commit is contained in:
Géry Debongnie
2019-03-22 09:52:48 +01:00
parent a236ae396a
commit d48cb5aae4
9 changed files with 150 additions and 24 deletions
+2 -2
View File
@@ -1,7 +1,7 @@
import { QWeb } from "./qweb";
import { EventBus } from "./event_bus";
import { Component, PureComponent } from "./component";
import { Store, StoreMixin } from "./store";
import { Store, connect } from "./store";
export const core = {
QWeb,
@@ -9,5 +9,5 @@ export const core = {
Component,
PureComponent,
Store,
StoreMixin
connect
};
+37 -6
View File
@@ -1,10 +1,41 @@
import { EventBus } from "./event_bus";
import { Component } from "./component";
import { shallowEqual } from "./utils";
export function StoreMixin(Component) {
return class extends Component {
mounted() {
this.env.store.on("update", this, this.render);
}
export function connect(mapStateToProps) {
return function(Comp) {
return class extends Comp {
constructor(parent, props?: any) {
const env = parent instanceof Component ? parent.env : parent;
const storeProps = mapStateToProps(env.store.state);
props = Object.assign(props || {}, storeProps);
super(parent, props);
this.__widget__.currentStoreProps = storeProps;
}
mounted() {
this.env.store.on("update", this, () => {
const storeProps = mapStateToProps(this.env.store.state);
if (!shallowEqual(storeProps, this.__widget__.currentStoreProps)) {
this.__widget__.currentStoreProps = storeProps;
// probably not optimal, will do 2 object.assign, one here and
// one in updateProps.
const nextProps = Object.assign(
{},
this.props,
this.__widget__.currentStoreProps
);
this.updateProps(nextProps, false);
}
});
}
willUnmount() {
this.env.store.off("update", this);
}
updateProps(nextProps, forceUpdate) {
nextProps = Object.assign(nextProps, this.__widget__.currentStoreProps);
return super.updateProps(nextProps, forceUpdate);
}
};
};
}
@@ -53,7 +84,7 @@ export class Store extends EventBus {
await Promise.resolve();
if (this._isMutating) {
this._isMutating = false;
this.trigger("update");
this.trigger("update", this.state);
}
}
+13
View File
@@ -112,3 +112,16 @@ export function findInTree<T extends Tree<T>>(
}
return null;
}
export function shallowEqual(objA, objB) {
if (objA === objB) {
return true;
}
const keysA = Object.keys(objA);
for (let key of keysA) {
if (!(key in objB) || objA[key] !== objB[key]) {
return false;
}
}
return true;
}