简体   繁体   中英

How add event listeners dynamically

I have some code (jQuery):

$(document).on('tap', '#category1-btn', {category : "category1"}, onlineListGen);
$(document).on('tap', '#category2-btn', {category : "category2"}, onlineListGen);
$(document).on('tap', '#category3-btn', {category : "category3"}, onlineListGen);
$(document).on('tap', '#category4-btn', {category : "category4"}, onlineListGen);
$(document).on('tap', '#category5-btn', {category : "category5"}, onlineListGen);
$(document).on('tap', '#category6-btn', {category : "category6"}, onlineListGen);

This seems to violate the DNRY rule. What's more, the number of categories is dependent on a JSON file that is read, and in future, I want to dynamically create the categoryN-btn(s) depending on the JSON file contents. AS such is there a way to do the above with either dynamically generating the event listeners or somehow doing it with classes?

Use a for loop :

var count = N; //N is the count of button from JSON

for(var i=0;i<count;i++){
     $(document).on('tap', '#category'+i+'-btn', {category : "category"+i}, onlineListGen);
}

Hope this helps.

You could wrap one of those in a function, and just call it whenever.

var tapper = (function(){
  var c = 0;
  return function(){
    $(document).on('tap', '#category'+(++c)+'-btn', {category : 'category'+c}, onlineListGen);
    return $;
  }
})();
tapper(); tapper(); // call whenever and wherever

As always the idea came to me just after I posted here.

I simply added this to my event handler function

function myFunction(){
  var category = this.id.slice(0,-4); //the slice removes the '-btn' from the ID
  myData = JSONData[category]
  //some more code that uses myData
}

and used the event listener

$(document).on('tap', '.category-btn', myFunction);

where the html for the button is

<a href="#category-1" class="category-btn" id= "category1-btn">category</a>

Assuming that you know what element type these categories are, you can add a handler which works generically (assuming a button for the element with has the #categoryX-btn ID - adjust to match your markup):

$(document).on('tap', 'button', function(ev) {
    var match = /^(category[0-9]+)-btn$/.exec(this.id);
    if (match) {
        ev.data = { category: match[1] };
        return onlineListGen.call(this, ev);
    }
    return true;
});

Not tested, but you should get the idea...

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