I'm working off of a module that's built in knockout.js and I want to map changes to observables onto an event stream after the manner of RxJs, highland.js or bacon.js.
I know there are ways to do this by extending knockout, like ko.subscribable.fn.someFilter
. But that assumes I want knockout to do my work for me - I don't, particularly.
Typically in Bacon or highland you would see something like this:
//bacon
var strm1 = $('#el').toEventStream('click');
strm1.map(transformFn);
//highland
var strm2 = _('click',$('#el'));
strm2.map(transformFn);
Unfortunately in knockout I'm not able to find an easy way to hook onto events since knockout implements pub/sub rather than emitters. Any insights into how I might hook on?
I was thinking something like a mediator emitter that subscribes to all observable properties and then emits the events.
assuming I have something like this bound by a ko viewmodel:
<input data-bind="value:name" />
and the viewmodel is something like
function Person(){
this.name = ko.observable('Bob');
this.age = ko.observable(21);
//...
};
var person = new Person();
var emitter = Emitter({});
var streams = {};
and then I am mapping as follows, where _
is highland.
for(var key in person){
streams[key]=_(key+':changed',watcher);
person[key].subscribe(function(){
watcher.emit(key+':changed',arguments);
});
}
function streamHandler(){
console.log('streamHandler got',arguments);
}
All well and good, my emitter fires just fine,but then this does nothing:
streams['name'].each(streamHandler);
So, I am missing something. What's wrong?