Last active
August 29, 2015 14:22
-
-
Save a-s-o/0911caf8f29d2195acef to your computer and use it in GitHub Desktop.
Kefir model
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
///////////// | |
// Factory // | |
///////////// | |
Kefir.model = function (store, tx) { | |
if (typeof tx !== 'function') tx = x => x; | |
const getset = function kefir$model (update) { | |
if (arguments.length > 0) { | |
let value = tx(update, (getset._currentEvent || {}).value); | |
if (getset._alive) { | |
// Active property (kefir will update current value) | |
getset._emitValue(value); | |
} else { | |
// In-active property (manually set current value) | |
getset._currentEvent = { type: VALUE, value: value }; | |
} | |
return value; | |
} | |
return (getset._currentEvent || {}).value; | |
}; | |
// Copy property methods to model | |
let proto = Kefir.Property.prototype; | |
for (var x in proto) getset[x] = proto[x]; | |
Kefir.Property.call(getset); | |
getset._currentEvent = { type: VALUE, value: store }; | |
return getset; | |
}; | |
/////////////// | |
// Converter // | |
/////////////// | |
Kefir.Observable.prototype.toModel = function(store, tx) { | |
if (typeof tx !== 'function') tx = x => x; | |
// Sources | |
let model = Kefir.model(store, tx); | |
let obs = this.map(update => tx(update, store)); | |
let getset = function (update) { | |
if (arguments.length > 0) { | |
store = model(update); | |
} | |
return store; | |
}; | |
// Output | |
const combined = Kefir | |
.merge([model.skip(1), obs]) | |
.map(val => (store = val)) // Assignment | |
.toProperty(() => store); | |
for (let x in combined) getset[x] = combined[x]; | |
return getset; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
Both methods expect the following arguments. The transformer function if provided receives (inputValue, currentModelState) as arguments and is expected to return the update model state.
Arguments
Returns
(Function): Getter/setter function. Call without an argument to get latest model state. Call with a single argument to set new model state.