The old event management, in which each action handler is directly tied to the target element, is becoming obsolete as concerns about performance and memory preservation began to spread in the development community.
Event delegation implementations have been accelerated since jQuery updated old-fashioned methods .bind()and .live()using a new method .on()to allow delegation.
This defines a change in some customized approaches where rework is needed to use event delegation. I am trying to develop some kind of best practice, keeping the coding style in my library, and looking for similar situations that other developers face in order to find the answer.
Using OOP with functions as constructors, I usually have interfaces for creating objects as follows:
var widget = new Widget({
timeout: 800,
expander: '.expanders'
});
with object literals specified as an argument, providing a clean map of the names and values of the input passed. The class underlying this code might be something like this:
var Widget = function(options) {
var _timeout;
var _$widget;
var _$expander;
this.init = function() {
_timeout = options.timeout || 500;
_$expander = $(options.expander);
_$widget = _$expander.next();
_$expander.on('click', _toggle);
};
var _toggle = function(e) {
if (_$widget.is(':visible')) {
_$widget.hide(_timeout);
} else {
_$widget.show(_timeout);
}
};
this.init();
};
"private" ( ), ( , ). , .
, :
this.toggle = function(e) {
if (_$widget.is(':visible')) {
_$widget.hide(_timeout);
} else {
_$widget.show(_timeout);
}
};
-, - :
var widget = new Widget({
expander: '.expanders'
});
$(delegationContext).on('click', '.expanders', widget.toggle);
, , , , :
var widget = new Widget({
timeout: 800,
expander: {
delegationContext: '.widgetContainer',
selector: '.expanders'
}
});
:
var $context = $(options.expander.delegationContext);
$context.on('click', options.expander.selector, _toggle);
?
, ?