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

2

8

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

Exuberate answered 14/5, 2015 at 23:15 Comment(0)
G
8

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/

Guevara answered 15/5, 2015 at 9:20 Comment(1)
This is right way to do it. Also emitter.emit can be passed directly as a callback — Mousetrap.bind('left', emitter.emit), unless you need that log of course.Grotto
L
2

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!

Labiche answered 15/5, 2015 at 8:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.