framework/js/lib/utils/subtree-retainer.js

39 lines
815 B
JavaScript
Raw Normal View History

2015-04-25 20:58:39 +08:00
/**
// constructor
this.subtree = new SubtreeRetainer(
() => this.props.post.freshness,
() => this.showing
);
this.subtree.check(() => this.props.user.freshness);
2015-04-25 20:58:39 +08:00
// view
this.subtree.retain() || 'expensive expression'
*/
export default class SubtreeRetainer {
constructor() {
this.invalidate();
2015-04-25 20:58:39 +08:00
this.callbacks = [].slice.call(arguments);
2015-05-18 09:05:12 +08:00
this.old = {};
2015-04-25 20:58:39 +08:00
}
retain() {
var needsRebuild = false;
this.callbacks.forEach((callback, i) => {
var result = callback();
if (result !== this.old[i]) {
this.old[i] = result;
needsRebuild = true;
}
});
return needsRebuild ? false : {subtree: 'retain'};
}
check() {
2015-04-25 20:58:39 +08:00
this.callbacks = this.callbacks.concat([].slice.call(arguments));
}
2015-05-04 09:13:40 +08:00
invalidate() {
2015-05-18 09:05:12 +08:00
this.old = {};
2015-05-04 09:13:40 +08:00
}
2015-04-25 20:58:39 +08:00
}