javascript - All click event handlers firing when a single click event triggered -
i've tried organize javascript using iifes make things more modular. however, i'm getting strange behaviour can't explain.
i have 2 divs:
<div id="one">foo</div> <div id="two">bar</div>
i have iifes to:
- lazy-load , cache elements
- define event listeners
- bind event listeners
- handle initialization
i try assign click handler each div
, when click on either div
, handlers fire. why?
(function(foobar) { foobar.elements = (function() { var one, two; return{ one: function(){ return 1 || (one = $('#one')); }, two: function(){ return 2 || (two = $('#two')); } } })(); foobar.eventlisteners = (function(elems){ return { oneonclick: function(e) { alert('1'); }, twoonclick: function(e) { alert('2'); } } })(foobar.elements); foobar.bindeventlisteners = (function(elems, listeners) { return function () { $(document).on('click', elems.one(), listeners.oneonclick); $(document).on('click', elems.two(), listeners.twoonclick); } })(foobar.elements, foobar.eventlisteners); foobar.init = function (options) { foobar.bindeventlisteners(); }; })(window.foobar = window.foobar || {}); foobar.init();
the delegated listener requires jquery selector not object (http://api.jquery.com/on/):
$(document).on('click', '#two', listeners.twoonclick);
so if change foobar.elements()
return selector string (eg:'#two'
) works:
Comments
Post a Comment