0

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?

matchdav
  • 715
  • 1
  • 7
  • 16
  • Are you asking whether your idea is correct conceptually? Or are you wanting some help debugging your specific implementation? – ColinE May 28 '14 at 05:53
  • I get that it's possible to force an observable to behave like an emitter - I've done it - but I just can't get the events to register as a stream now, so something is wrong with how I'm creating the emitter and then instantiating the stream. Maybe the stream should be instantiated later? – matchdav May 28 '14 at 06:00

0 Answers0