Rudimentary support for comparators.
This commit is contained in:
parent
a26d268f8a
commit
363aa34e85
@ -1,4 +1,4 @@
|
|||||||
export function computed(fn, dependencies = []) {
|
export function computed(fn, dependencies = [], comparator = eq) {
|
||||||
const subscribers = new Set();
|
const subscribers = new Set();
|
||||||
const dependents = new Set();
|
const dependents = new Set();
|
||||||
let isDirty = true;
|
let isDirty = true;
|
||||||
@ -21,7 +21,7 @@ export function computed(fn, dependencies = []) {
|
|||||||
if (isDirty) {
|
if (isDirty) {
|
||||||
const newVal = fn.apply(null, dependencies.map(runParam));
|
const newVal = fn.apply(null, dependencies.map(runParam));
|
||||||
isDirty = false;
|
isDirty = false;
|
||||||
if (newVal !== val) {
|
if (!comparator(newVal, val)) {
|
||||||
val = newVal;
|
val = newVal;
|
||||||
subscribers.forEach(s => s(val));
|
subscribers.forEach(s => s(val));
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,8 +1,10 @@
|
|||||||
export function observable(store) {
|
import { eq } from './util.js';
|
||||||
|
|
||||||
|
export function observable(store, comparator = eq) {
|
||||||
const subscribers = new Set();
|
const subscribers = new Set();
|
||||||
|
|
||||||
const accessor = function _observable(newVal) {
|
const accessor = function _observable(newVal) {
|
||||||
if (newVal !== undefined && store !== newVal) {
|
if (newVal !== undefined && !comparator(store, newVal)) {
|
||||||
store = newVal;
|
store = newVal;
|
||||||
subscribers.forEach(s => s(store));
|
subscribers.forEach(s => s(store));
|
||||||
}
|
}
|
||||||
|
|||||||
1
src/util.js
Normal file
1
src/util.js
Normal file
@ -0,0 +1 @@
|
|||||||
|
export const eq = (a, b) => a === b;
|
||||||
Reference in New Issue
Block a user