Answer the question
In order to leave comments, you need to log in
Is there a similar pattern for binding javascript events to the DOM?
Good afternoon. It would be interesting to know if a similar approach to binding DOM elements with javascript events has the right to exist:
jQuery.fn.eventHandler = function(){
/*объект для хранения функций, применяемых к DOM элементам*/
var function_storage = {
testAlert : function(obj, args){
alert(obj);
alert(args);
},
testLog : function(obj, args){
console.log(obj);
console.log(args);
}
}
this.each(function() {
var event = $(this).data('event'),
args = $(this).data('args'),
func = $(this).data('func'),
if (func != null) {
if (event == null) {
event = 'click';
}
$(this).on(event, function (e) {
e.preventDefault();
function_storage[func]($(this), args);
});
}
});
};
$(document).ready(function(){
$('.eventHandler').eventHandler();
});
<div class="eventHandler" data-func="testAlert" data-event="mouseenter" data-args="test">Навешиваем mouseenter на div</div>
Answer the question
In order to leave comments, you need to log in
In general, the norms, something similar is used in Angular (ng-click directive). Only there everything is a little more complicated.
And if I need to hang several events on one block? Then it makes sense to pass an array of events like data-events='["click","mouseenter","mouseleave"]' and an array of corresponding handlers. And in general, I would formalize this by passing an object, where the key is an event, and the value is a handler (well, shove the arguments there too somewhere).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question