Search code examples
javascriptdom-eventsanonymous-functionmobile-website

Anonymous function references in Javascript


I'm currently in the process of building out a VERY simple Observer class for a project I'm working on. I have successfully implemented the subscribe, unsubscribe, and notify methods. Everything works exactly as expected when using "regular" functions (i.e: var f = function()).

However, when I pass an anonymous function to the subscribe method and then try to unsubscribe passing the "same" anonymous function it (as expected) doesn't remove the function from my array (they are different, after all).

Here's my subscribe and unsubscribe methods:

this._subscribers = {};
subscribe: function(type, callback) {
    if ( isUndefined(this._subscribers[type]) ) {
        this._subscribers[type] = [];
    }
    this._subscribers[type].push(callback);
},
unsubscribe: function(type, callback) {
    if ( this._subscribers[type] instanceof Array ) {
        var index = this._subscribers[type].indexOf(callback);
        if ( index >= 0 ) {
            this._subscribers[type].splice(index, 1);
        }
    }
},

And here's the code I'm testing with:

var o = new gaf.events.Observable();
o.subscribe('testEvent', function(event) { alert('Got It!'); });
o.notify('testEvent');
// Correct alerts 'Got It!'
o.unsubscribe('testEvent', function(event) { alert('Got It!'); });
o.notify('testEvent')
// Incorrectly alerts 'Got It!'

I know I could using an object (i.e.: _subscribers[event] = {}) and then when something subscribes I could add a new property equal to the callback and the value equal to the callback. This will cause Javascript to convert the callback to the string. I could then look it up (provided the methods passed in sub/unsub are exactly the same) using that string.

However, this is a mobile project and I'm very leery about storing strings that could be hundreds of characters long as properties as we could end up with a lot of subscribers.

Are there any other ways of doing this? Are there any SMALL (tiny, even) hashing libraries I can use to maybe hash the string value of the function and use that as the property? Would it be better to store the string value of the callback (so I can compare against it) in the array (rather then the actual callback) and use eval() on it?

EDIT

First, thanks all for the replies!

Per all the questions about "Why even pass anonymous" functions -

There really is no reason one COULDN'T use named functions. In fact, I agree with everyone that named functions are going to be the better solution. I'm simply gathering information and looking for a solution so that I can build out an implementation that handles the most scenarios as best as possible.

The other reason for this is what happens if a user (co-worker) of this Observable class passes it an anonymous function and then unsubscribes. That function won't actually be unsubscribed and therefore won't be cleaned up. I have a thing against orphaned data :)

Maybe another question I should as is, is it possible to test if the callback is anonymous or not? I'm going to assume no but doesn't hurt to ask.


Solution

  • Perhaps a better solution is to modify the code using your library

    var f = function() { alert('Got It!'); };
    o.subscribe('testEvent', f);
    o.notify('testEvent');
    o.unsubscribe('testEvent', f);
    o.notify('testEvent');
    

    You could even return the function from the subscribe method

    var f = o.subscribe('testEvent', function() { alert('Got It!'); });
    // ...
    

    then if you want to store a hash or some other identifier for subscribed functions, it is opaque to the calling code meaning that you just use the returned value to unsubscribe and the library hides the implementation detail.