I'd try adding a self executing anonymous closure function:
Code:
$.fn.game = function(args) {
for(var key in args.objects) {
if(typeof args.objects[key].exec.keydown == "function") {
(function(k, f){
$("#" + k).mousedown(f);
})(key, args.objects[key].exec.mousedown);
}
}
}
Either way, all I get is:
Cannot read property 'keydown' of undefined
I'm assuming that's not the case in the actual code environment. If it is, nothing will work.
Here's a working example:
Code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
</head>
<body>
<div id="main">Main</div>
<div id="enemy">Enemy</div>
<script type="text/javascript">
$.fn.game = function(args) {
for(var key in args.objects) {
if(typeof args.objects[key].exec.keydown == "function") {
(function(k, f){
$("#" + k).mousedown(f);
})(key, args.objects[key].exec.mousedown);
}
}
}
$("#gameParent").game({
objects : {
main : {
exec : {
mousedown : function() {
console.log("test");
},
keydown: function(){}
}
},
enemy : {
exec : {
mousedown : function() {
console.log("test2");
},
keydown: function(){}
}
}
}
});
</script>
</body>
</html>
Here's another solution:
Code:
$.fn.game = function(args) {
for(var key in args.objects) {
if(typeof args.objects[key].exec.keydown == "function") {
$("#" + key).mousedown(function() {
args.objects[this.id].exec.mousedown();
});
}
}
}
But, since it relies upon the coincidence that key is the element's id, it's not as widely applicable.
If you want more help, please include a link to the page on your site that contains the problematic code so we can check it out.
Bookmarks