Deactivating events with .off

Most of my .on events use closures:

ref.on( 'child_added', function( snapshot ) { userCallback( snapshot.val() ); } ); 

which means that it is not possible to turn off these monitors using .off (), since off needs the original callback pointer, as well as eventType. How can i do this?

My app (jQuery Mobile) is page based. When a user clicks on a specific page, I want to activate monitors. When the user leaves this page, I want to deactivate, so when they are entered again, I do not get multiple monitors. I think I want to call .off () only with eventType and remove all callbacks.

+4
source share
2 answers

Currently, the only option is to keep the callback link. We actually simplified this a bit by getting .on () to return it back to you. So you can do:

 var childCallback = ref.on('child_added', function(snapshot) { /* whatever */ }); // later... ref.off('child_added', childCallback); 

But we got some feedback, for example yours, stating that it’s sometimes difficult to keep track of your callbacks. So we have a planned change to the API so that you can call .off () only with the event type or without any arguments, and we just delete all the callbacks. But now we are focusing on other functions, so this change is probably 1 year.

Thanks for the feedback!

+5
source

In the meantime, you can reproduce this behavior with a simple manager template. For instance:

 function ObserverManager( firebaseRef, page ) { this.firebaseRef = firebaseRef; this.listeners = {child_added: [], child_removed: [], value: [], child_updated: [], child_changed: []}; this.page = page; } FirebaseObservable.prototype.on(event, callback) { this.listeners[event].push( this.firebaseRef.on(event, function(snapshot) { callback(snapshot.val()); }) ); } FirebaseObservable.prototype.off(event) { var list = this.listeners[event], i = list.length; while(i--) { // 50% more efficient than for(i..; list.length; ...) in IE due to scoping firebaseRef.off(event, list[i]); } } 
+2
source

All Articles