V
V
vldud2015-04-07 09:59:37
JavaScript
vldud, 2015-04-07 09:59:37

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();
});

In this case, events are added directly to the HTML:
<div class="eventHandler" data-func="testAlert" data-event="mouseenter" data-args="test">Навешиваем mouseenter на div</div>

Interested in the pros and cons of this approach, primarily in terms of performance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2015-04-07
Protko @Fesor

In general, the norms, something similar is used in Angular (ng-click directive). Only there everything is a little more complicated.

T
teotlu, 2015-04-08
@teotlu

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 question

Ask a Question

731 491 924 answers to any question