0

So lets say I have a button #button. I want it to toggle visibility of some element #element. So with plain jQuery I would do

$("#button").on("click", function() {$("#element").toggle();})

Or with an explicit side-effect:

var visible = true;
$("#button").on("click", function() {visible = !visible; $("#element").show(visible);})

What would be the equivalent of this in Bacon.js. I would assume it's possible to do without any side-effects, but I can't figure it out how.

EDIT: Let me clarify: without any side-effect which aren't a part of Bacon.js-objects.

Dimitri Vorona
  • 450
  • 3
  • 13

2 Answers2

2

The docs give an almost literal example on how to do that with .assign and $.fn.asEventStream:

$("#button").asEventStream("click").assign($("#element"), "toggle");

Caveats: with an event stream you can't use the Property::assign method, yet onValue works the same way. Also we want to ensure that toggle isn't invoked with the event as an argument, so you'd rather use

$("#button").asEventStream("click").onValue($("#element"), "toggle", null, null);

For explicit state, we use the scan method:

$("#button").asEventStream("click") // a stream of click events
.scan(true, // iterate it, starting with true
      function(visible, e) {
     // ignore the event parameter
     return !visible; // just toggle the boolean
}) // now we've got a property of a changing boolean value
.assign($("#element"), "show");
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

I'm not entirely positive about this, but it appears that Bacon.js relies on either jQuery or Zepto to function properly. From the API Documentation on GitHub:

API Creating streams

$.asEventStream(eventName) creates an EventStream from events on a jQuery or Zepto.js object. You can pass optional arguments to add a jQuery live selector and/or a function that processes the jQuery event and its parameters, if given, like this:

$("#my-div").asEventStream("click", ".more-specific-selector")
$("#my-div").asEventStream("click", ".more-specific-selector", function(event, args) { return args[0] })
$("#my-div").asEventStream("click", function(event, args) { return args[0] })

For what its worth, here's a fiddle that shows how you would do this in vanilla JavaScript:

http://jsfiddle.net/cs01rm3v/

bazeblackwood
  • 1,127
  • 6
  • 16