Skip to content

Instantly share code, notes, and snippets.

@noxecane
Forked from anonymous/index.html
Last active November 28, 2015 23:17
Show Gist options
  • Save noxecane/09c971c4b3ffbc31e2b6 to your computer and use it in GitHub Desktop.
Save noxecane/09c971c4b3ffbc31e2b6 to your computer and use it in GitHub Desktop.
Data binding implementation in es6
export class KeyPath {
static lastValue(keypath, object) {
return keypath.split('.').reduce((prev, curr) => {
return prev && prev[curr];
}, data);
}
static lastKey(keypath, object) {
return keypath.split('.').pop();
}
static keyUp(keypath) {
keypath = keypath.split('.');
keypath.pop();
return keypath.join('.')
}
static keyDown(keypath, next) {
keypath = keypath.split('.');
keypath.push(next);
return keypath.join('.');
}
static lastObject(keypath, object) {
return KeyPath.lastValue(KeyPath.keyUp(), object);
}
}
import {KeyPath} from './keypath.es';
export class Observable {
static simpleProperty(object, prop, watcher) {
var config = {enumerable: true};
Object.defineProperty(object, `__${prop}__`, {
enumerable: false,
value: object[prop]
});
config.get = () => {
return object[`__${prop}__`];
}
config.set = (newVal) => {
watcher(newVal, object[prop]);
object[`__${prop}__`] = newVal;
};
Object.defineProperty(object, prop, config);
}
static array(array, watcher) {
// hide defualt implementations
['push', 'pop', 'shift', 'unshift'].forEach((prop) =>{
Object.defineProperty(array, `__${prop}__`, {
enumerable: false,
value: array[prop]
});
});
Object.defineProperties(array, {
assign: {
enumerable: false,
writable: false,
value: (index, val) => {
var oldArray = new Array(...array);
var oldItem = array[index];
watcher(array, oldArray, val, oldItem, index);
}
},
push: {
enumerable: false,
writable: false,
value: (...args) => {
args.forEach(function (item) {
var oldArray = new Array(...array);
array.__push__(item);
watcher(array, oldArray, item);
});
return array.length;
}
},
pop: {
enumerable: false,
writable: false,
value: () => {
var oldArray = new Array(...array);
var item = array.__pop__();
watcher(array, oldArray, item);
}
},
shift: {
enumerable: false,
writable: false,
value: () => {
var oldArray = new Array(...array);
var item = array.__shift__();
watcher(array, oldArray, item);
}
},
unshift: {
enumerable: false,
writable: false,
value: (...args) => {
args.forEach(function (item) {
var oldArray = new Array(...array);
array.__unshift__(item);
watcher(array, oldArray, item);
});
return array.length;
}
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment