List in a Container with Bacon.js

210 Views Asked by At

I have a list of elements and a container for the list. (They are implemented with Marionette + Backbone views).

What I'd like to do is register a click on the list and send it to the container with bacon.js or something similar.

This is fairly easy with something like: this.selected = this.$el.asEventStream('click').map(this);, so that I can highlight the selected item.

The problem now is that as soon as another element is selected the old one must be unselected, and I'm not sure what strategy to use here.

I'd like not to mutate the list from the container.

Edit to clarify:

The code I have at the moment is here:

https://github.com/archaeron/Marionette.CompoundView

And I'm still doing this with traditional events, but I'd like to try another way of doing it.

1

There are 1 best solutions below

2
On

I don't know how to implement it correctly with Backbone, but with Bacon alone I would do something like this:

$container = $('.container')

itemClicks = $container.asEventStream('click', '.item').map (event) ->
  $(event.target)

nonContainerClicks = $(document).asEventStream('click').filter (event) ->
  not $.contains($container.get(0), event.target)

selectedItem = Bacon.mergeAll(
  itemClicks,
  nonContainerClicks.map(-> null)
).toProperty(null)

selectedItem.onValue (itemEl) ->
  $('.container').find('.item.selected').removeClass('selected')
  if itemEl isnt null
    itemEl.addClass('selected')

Don't sure if it helps, but may be will give you some thoughts at least.