سؤال

I'm learning to use the fantastic Bacon.js library for functional reactive programming. Adding handlers to a property or stream is easy:

handler = function(value){... do something ...}
property.onValue(handler)

Say somewhere down the line I want to cancel this subscription, like this (pseudocode):

property.unsubscribe(handler)

Is there a way to do this with Bacon.js?

هل كانت مفيدة؟

المحلول 2

From the "cleaning up" section of the docs:

Call the dispose() function that was returned by the subscribe() call.

So you have to save the return of onValue:

var dispose = property.onValue(handler)

Then invoke it to remove the listener:

dispose();

Here's a demo.

نصائح أخرى

Both answers above are correct. Personally, I've never used either solution though. In fact, they mainly exist for internal purposes and for writing custom combinators and integrations.

So instead I recommend combinators like take, takeWhile and takeUntil. In an FRP application, the signal that triggers the need can usually be modeled as an EventStream. In that case you can do

var data, stopper // EventStreams
data.takeUntil(stopper).onValue( .. )

From the documentation:

stream.subscribe(f) subscribes given handler function to event stream. Function will receive Event objects (see below). The subscribe() call returns a unsubscribe function that you can call to unsubscribe. You can also unsubscribe by returning Bacon.noMore from the handler function as a reply to an Event.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top