1

I'm working with a home-grown javascript library that has event handling. At it's core is a registerEvents function:

core.registerEvents = function(evts, mod)
{
    if (this.is_obj(evts) && mod)
    {
        if (moduleData[mod])
        {
            moduleData[mod].events = evts;
        }
    }
};

In this, mod is a module, moduleData is an array of modules that is in the functions parent scope, and evts is an object with named functions. Use is something like:

core.registerEvents({
        "event1": function() {alert('event1');},
        "event2": function() {alert('event2');}
    },
    myModule);

This is all working well, except that it requires all the events to be registered at once, there's no ability to register an additional event, later.

What I would like is to extend this so that when you call registerEvents(), if there are no events registered you accept the passed evts object as your events object, but if there are already events registered, then you add the functions in your evts object to your events object.

Something like this:

core.registerEvents = function(evts, mod)
{
    if (this.is_obj(evts) && mod)
    {
        if (moduleData[mod])
        {
            if (moduleData[mod].events)
            {
                // move functions in evts to moduleData[mod].events
            }
            else
            {
                moduleData[mod].events = evts;
            }
        }
    }
};

And I haven't a clue as to how to do it.

One complexity: Our new function, evts.event1, was defined in a particular lexical scope. When we move the function to another object, we don't want to change that scope. The variables that were in the parent scope when evts.event1 was defined should remain accessible to evts.event1, even after it's been moved to another object.

I'm at a loss. Help would be appreciated.

nitishagar
  • 9,038
  • 3
  • 28
  • 40
Jeff Dege
  • 11,190
  • 22
  • 96
  • 165
  • For the preserving the scope, take a look at [`bind`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) – Sean Vieira Jan 30 '15 at 16:56
  • After a function has been created, its scope cannot change anyway. As you said, JavaScript has *lexical* scope, not *dynamic* scope. The scope of a function is only defined by where it is located in the source code, not where it is executed. – Felix Kling Jan 30 '15 at 16:59
  • _.forEach( _.functions(b), function(fn){ a[fn] = b[fn] }); – makeitmorehuman Jan 30 '15 at 17:08
  • One example of copying functions I ran across when searching prior to asking the question involved extracting the function as a string, and creating a new function with eval(). Which would break scoping. – Jeff Dege Jan 30 '15 at 17:25

0 Answers0