简体   繁体   中英

Using jQuery to listen for DOM events vs html handles

Originally I wrote standard functions triggered by an on input event handler that I placed in the HTML. However, it was recommended to me to rather 'listen' for events using jQuery (to make for more readable code).

Question: What is the difference in terms of processing between the two? (as in how is the code of each style interacting with the DOM).

Originally I had something like this:

HTML:

<input type='range' oninput='doStuff()'../>

JS:

function doStuff() {
  //Things happen
}

Below is the refactored code:

var makeMusic = {
    var1: val,
    var2: val,
    var3: val,

    init: function() {      
        makeMusic.watchExperience();
    },

    watchExperience: function() {
        $(document).on('input change', '#input_experience', function() {
            //do stuff
        }
    },

    anotherFunction: function() {
    },

    etc
}

var otherScript = {
    init: function() {
    },

    etc
}


var Main = {
    run: function() {
        makeMusic.init();
        otherScript.init();
    }
}

$(document).ready(Main.run);

I think you are talking about custom event dispatchers and redirecting it to a standard event

Based on your example the orginal event given by the browser DOM which is onchange if you want to do a proxy for it then you definitely catch that event and trigger your oninput

Refer https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

You can capture all the events at document level or a wilcard ***** selector level and re-trigger oninput with a custom code

if you use JQuery it will also help

The difference is: you can handle the native hardware events in a more sophisticated manner. This allows you create your own framework which give more proper event names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM