I'm implementing the module pattern, and would like to know the best/preferred way to define and register event listeners/handlers. The following works, but maybe there is a better/simpler way...
var MODULE = function() {
// private
var _field1;
var _field2;
function localFunc(p) {
alert('localFunc');
}
// public
return {
// properties
prop1: _field1,
// events
myEvent1Handler: {},
myEvent1: function() {myEvent1Handler();},
myEvent2Handler: {},
myEvent2: function() {myEvent2Handler();},
addListener: function (event,func) {
if (event == "myEvent1")
myEvent1Handler = func;
if (event == "myEvent2")
myEvent2Handler = func;
},
// public methods
method1: function (p) {
alert('method1 says:' + p);
MODULE.myEvent1();
},
method2: function (p) {
alert('method2 doing stuff');
localFunc(p);
MODULE.myEvent2();
}
};
}();
// register for events
MODULE.addListener("myEvent1",function(){alert('fired1');});
MODULE.addListener("myEvent2",function(){alert('fired2');});
// use module (only event1 should fire!)
MODULE.method1("hello");
Try it out:
Seems like a lot of work to have myEventx, myEventHandlerx, and addListener?
addListener()
, isn't that creatingmyEvent1Handler
ormyEvent2Handler
as global variables referencing thefunc
parameter passed in? It won't be setting the properties of the same name already defined in your object unless you saythis.myEvent1Handler = ...
- and thenthis.myEvent1Handler()
in yourmyEvent1
function. (OrMODULE.myEvent1Handler
like how you haveMODULE.myEvent1()
inmethod1
.) – Bureau