Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kefir.js - How to stream events from a callback function?

Tags:

javascript

frp

The Mousetrap.js library lets you bind a callback function to keys like so:

Mousetrap.bind('space', function, 'keydown');

What's the best way to attach a stream to this without using the Bus of Doom? Should I use emitter or pool?

I'm trying to get arrow keys hooked up in this fiddle: jsfiddle.net/vzafq25w

like image 603
dpren Avatar asked May 14 '15 23:05

dpren


2 Answers

You can use general wrapper stream

var leftKeys = Kefir.stream(function(emitter){
    Mousetrap.bind('left', function(e) {
        emitter.emit(e);
        console.log(e);
    });
    return function(){
        // unbind
    };
});

http://jsfiddle.net/be9200kh/1/

like image 84
iofjuupasli Avatar answered Oct 30 '22 19:10

iofjuupasli


Normally, you can use Kefir.fromEvents, but in your case, where Mousetrap.js does not bind using on|off methods, you can instead just use Kefir.pool (Kefir.emitter was deprecated) and trigger Kefir in the Mousetrap callbacks. I modified your code to demonstrate using Kefir.pool in the Mousetrap callbacks: http://jsfiddle.net/be9200kh/

Basically, you do

var pool = Kefir.pool();
pool.plug(Kefir.constant(1));
pool.map(...).filter(etc)

Have fun!

like image 23
Greg Edwards Avatar answered Oct 30 '22 19:10

Greg Edwards