deroccha deroccha - 5 months ago 17
jQuery Question

RequireJS on jquery bind event does not fire method

Using requirejs with jquery I face a problem with method calling on binded event. Having the following code:



define(["jquery"], function($) {


function showRowItem(item) {
console.log('method in');

}

jQuery(document).ready(function () {

jQuery('ul#topnav-firstrow li').each(function () {

jQuery(this).bind("mouseover", function (event) {
if (outTimerID != null) {
clearTimeout(outTimerID);
outTimerID = null;
}
globalMouseOverItem = this;
inTimerID = window.setTimeout("showRowItem(globalMouseOverItem)", inDelay);
});

});
});

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>





when I hover on item event is getting fired but method not recognized

Uncaught ReferenceError: showRowItem is not defined


here is a codepen http://codepen.io/deroccha/pen/WxQLoy for reproducing the error

Answer

Passing a string to setTimeout is both bad and not necessary, and doing so causes the problem you ran into because the evaluation of the string is delayed and thus happens outside the context where showRowItem is available. You could do this instead:

window.setTimeout(showRowItem.bind(globalMouseOverItem), inDelay);

Or with the current code you have this would be equivalent:

window.setTimeout(showRowItem.bind(this), inDelay);

and you could omit globalMouseOverItem.

Comments