jQuery: creare un binding tra il nostro codice e gli elementi del documento

jQuery: creare un binding tra il nostro codice e gli elementi del documento

In jQuery possiamo implementare un binding tra il nostro codice e gli elementi della pagina.

Creiamo il binding usando gli attributi di dati:


<button type="button" data-action="saveData" data-event="click">Save</button>

Quindi avremo:


"use strict";

(function( $ ) {
    $.app = {
        actions: {
            saveData: function( element ) {
                
            }
        },
        init: function() {
            var self = this;
            $( "[data-action]" ).each(function() {
                var $el = $( this );
                var action = $el.data( "action" );
                var evt = $el.data( "event" );
                $el.on( evt, function( e ) {
                    if( evt == "click" || evt == "submit" ) {
                        e.preventDefault();
                    }
                    self.actions[action]( $el );
                });
            });      
        }
    };

    $(function() {
        $.app.init();
    });
})( jQuery );
Torna su