I am trying the understand the concept of adding event processing feature (at page no. 120) to objects explained by Crockford as in this example:
var eventuality = function (that) {
var registry = {};
that.fire = function (event) {
var array,
func,
handler,
i,
type = typeof event === 'string' ? event : event.type;
if (registry.hasOwnProperty(type)) {
array = registry[type];
for (i = 0; i < array.length; i += 1) {
handler = array[i];
// A handler record contains a method and an optional
// array of parameters. If the method is a name, look
// up the function.
func = handler.method;
if (typeof func === 'string') {
func = this[func];
}
// Invoke a handler. If the record contained
// parameters, then pass them. Otherwise, pass the
// event object.
func.apply(this,
handler.parameters || [event]);
}
}
return this;
};
that.on = function (type, method, parameters) {
// Register an event. Make a handler record. Put it
// in a handler array, making one if it doesn't yet
// exist for this type.
var handler = {
method: method,
parameters: parameters
};
if (registry.hasOwnProperty(type)) {
registry[type].push(handler);
} else {
registry[type] = [handler];
}
return this;
};
return that;
};
console.log('eventuality ', eventuality({name: "test"}));
Well, it adds methods on
and fire
but how do I use it in practical? I mean, it was briefly explained that on
and fire
events used for handling events when fired but didn't find an example on how to put it to implementation?
If any one could explain what is happening in the above example, it would be helpful. Thank you