Skip to content

Instantly share code, notes, and snippets.

@a-s-o
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save a-s-o/0911caf8f29d2195acef to your computer and use it in GitHub Desktop.
Save a-s-o/0911caf8f29d2195acef to your computer and use it in GitHub Desktop.
Kefir model
/////////////
// 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;
};
@a-s-o
Copy link
Author

a-s-o commented Jun 9, 2015

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

  1. seed (Any): The initial value of the model
  2. [transformer=identity] (Function): Transformer invoked for all incoming values; either from setter interface or (in case of obs.toModel(), additionally from the base observable)

Returns

(Function): Getter/setter function. Call without an argument to get latest model state. Call with a single argument to set new model state.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment