javascript - Dynamically setting event listeners (on click) in JQuery in a loop -
i iterate through array of custom objects, , each object in array create button on click event listener, setting results of on click event dynamically. in other words, click on button might result in alert 'foo', , click on button b might result on different behavior - alert 'bar'.
my jshint linter says "don't make functions within loop".
i hoping community share better design pattern achieving goal (vanilla js or jquery).
check out fiddle - extremely simplified version of doing, illustrates point.
javascript (es6):
class tool { constructor (name, mainfunction) { this.name = name; this.mainfunction = mainfunction; } getname() { return this.name; } getmainfunction() { return this.mainfunction; } } var hammer = new tool('hammer', 'bang on nails'); var saw = new tool('saw', 'cuts heavy wood'); var toolbox = [hammer, saw]; (let in toolbox) { $('.wrapper').append('<div class=\"'+toolbox[i].getname()+' button\">'+toolbox[i].getname()+'</div>'); $('.wrapper').on('click', '.'+toolbox[i].getname(), function() { alert(toolbox[i].getmainfunction()); }); }
html
<div class="wrapper"> buttons: </div>
you can assign click functionality shared class .button
, assign messages data
attribute: demo
class tool { constructor (name, mainfunction) { this.name = name; this.mainfunction = mainfunction; } getname() { return this.name; } getmainfunction() { return this.mainfunction; } } var hammer = new tool('hammer', 'bang on nails'); var saw = new tool('saw', 'cuts heavy wood'); var toolbox = [hammer, saw]; (let in toolbox) { $('.wrapper').append('<div data-message="'+toolbox[i].getmainfunction()+'" class=\"'+toolbox[i].getname()+' button\">'+toolbox[i].getname()+'</div>'); } $('.wrapper').on('click', '.button', function() { alert($(this).data('message')); });
Comments
Post a Comment