Search code examples
javascriptasynchronousfunctional-programmingbacon.js

Functional Javascript BaconJS, how can I push more values to an event stream?


I'm attempting to create a stack of AJAX responses in BaconJS. That processes them in a first in first out fashion, but each 'out' event should wait for user input.

This is where I'm at now: Live JSBin

var pages = Bacon.fromArray([1,2,3])
var next = $("#next").asEventStream('click').map(true);

pages.flatMapConcat(asyncFunction).zip(next).log("responses")

function asyncFunction(page) {
  // Simulating something like an AJAX request
  return Bacon.later(1000 + (Math.random() * 3000), "Page "+ page)
}

Currently this synchronously outputs an event from the pages EventStream each time that #next is clicked, which the behavior I want.


However, I am unable to figure out how to push more values to the pages EventStream. I have attempted to replace the pages EventStream with a Bus, and pushing values like this (which doesn't work).

var pages = new Bacon.Bus()
pages.push("value")

How do I push more values to an EventStream?


Solution

  • I know this is an OLD post, but bus would work. Just push the number (you had an array of numbers before) into it:

    var pages = new Bacon.Bus();
    // Bacon.fromArray([1,2,3])
    var next = $("#next").asEventStream('click').map(true);
    
    pages.flatMapConcat(asyncFunction).zip(next).log("responses")
    
    function asyncFunction(page) {
      // Simulating something like an AJAX request
      return Bacon.later(1000 + (Math.random() * 3000), "Page "+ page)
    }
    
    
    pages.push(1);
    pages.push(2);
    pages.push(3);
    

    I cloned your jsbin and changed it to use bus

    As mentioned previously, you could stream the source of the page values using something like fromEvent or from fromBinder