Monday, 9 October 2017

javascript: pass local variables to anonymous function





Question: how to access
shortcut or action or other local
variables



Related:
Similar questions but not
success:






Java
Solution:

set final modifier to
variables that required in anonymous
function



Target Source
code:



//plugin.buttons
is collection of button objects
for (var i in plugin.buttons) {
var
button = plugin.buttons[i];

var icon = button.icon;
var
text = button.text;
var shortcut = button.shortcut;
var action =
button.action; //action is a function ( or method )

if (shortcut
!= null && shortcut.length > 0) {
if ($.isFunction(action))
{
console.log(shortcut); //it's valid shortcut
//using jQuery
hotkey plugin
$('div[contenteditable]').bind('keydown', shortcut, function ()
{

console.log(shortcut); //it's undefined

action.call(); //it's undefined also
return false;
});

}
}
}


Answer




You can pass it in as href="http://api.jquery.com/event.data/" rel="nofollow">event
data




for
(var i in plugin.buttons) {
var button = plugin.buttons[i];
var
icon = button.icon;
var text = button.text;
var shortcut =
button.shortcut;
var action = button.action; //action is a function ( or
method )

if (shortcut != null && shortcut.length > 0)
{
if ($.isFunction(action)) {



$('div[contenteditable]').on('keydown', {shortcut : shortcut}, function (e)
{

console.log(e.data.shortcut);


});
}

}
}



But
in this case the real issue is that there is no special scope in a for loop, so defining
variables inside the for loop just overwrites the same variables on each iteration,
which is why it doesn't work when the event handler is called at a later
time.



You have to lock in the variable in a new
scope



for (var key in
plugin.buttons) {
(function(i) {
var button =
plugin.buttons[i];
var icon = button.icon;
var text =
button.text;

var shortcut = button.shortcut;
var action
= button.action; //action is a function ( or method )

if (shortcut
!= null && shortcut.length > 0) {
if ($.isFunction(action))
{
console.log(shortcut); //it's valid shortcut
//using jQuery
hotkey plugin
$('div[contenteditable]').bind('keydown', shortcut, function ()
{
console.log(shortcut); //it's undefined
action.call(); //it's
undefined also

return false;
});

}
}

})(key);
}


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...