Syntactic sugar for jQuery selection using data-hook attributes.
Based on an article written by Will Boyd: Effective Event Binding with jQuery.
License: MIT
- jQuery (any version)
Using bower:
bower install jquery --save
bower install jquery.datahook --save`
It extends jQuery adding the $.datahook()
method.
$.datahook(hookName)
selects elements through data-hook
attributes:
- $.datahook(): Selects all the hook elements.
- $.datahook('*'): Same as
$.datahook()
. - $.datahook('name'): Selects elements with a
data-hook
attribute containingname
(adata-hook
attribute can be a single name or a space-separated list of names).
Alternatively, it is possible to use the $.hook()
alias.
If another hook-related jQuery plugin uses $.hook()
, jquery.datahook
will not register it as alias to prevent conflicts.
Short answer: Separation of concerns.
Long answer: The "select-by-class" approach is very common when using jQuery, but that leads to rely on a class for presentation and behaviour. It would be possible to rename or remove it due to some CSS refactoring and forget it was being used in Javascript too. Changes related to CSS should not affect to behaviour.
"Attribute contains word" selector is relatively slower than "class" selector, as shown in this jsPerf benchmark, but it can perform thousands of operations per second. This is not a bottleneck.
The pros of separating the concerns are considerable (code is more maintainable and less error-prone) and the cons (slower selection) are unnoticeable.