[英]How can I name a function after the value of a variable?
I have a function that allows you to load a new image. 我有一个允许您加载新图像的功能。 I want that function to make a function that detects when that image is loaded, and store it in an array or object. 我希望该函数能够创建一个检测何时加载该图像并将其存储在数组或对象中的函数。 I have another function that will go through the array or object, and check each to see if it's loaded. 我还有另一个函数,它将遍历数组或对象,并检查每个函数以查看是否已加载。
My question is, how can I add each new function to the array, and have each one return whether the image it's set to check is loaded or not? 我的问题是,如何将每个新函数添加到数组中,并让每个函数返回设置为检查的图像是否已加载?
** edit ** **编辑**
I want to pass a name to the function that loads images, to load 'images/'+name+'.png'
and then pass the name to the array or object as the name of the key. 我想将名称传递给加载图像的函数,以加载'images/'+name+'.png'
,然后将该名称传递给数组或对象作为键名。
** In reply to Shawn31313: here is the basic for what I have: **回复Shawn31313:这是我所拥有的基本知识:
var resources = {
// I have other stuff to load here
'newImg': function(name) {
if (name) {
var img = new Image();
img.src = 'images/' + name + '.png';
imgLoadingArray[name] = function () {
var loaded = false;
// detect image loading some how
}
}
},
'imgLoadingArray': {},
'loaded': function() {
var loaded = true;
for (each in game.resources.imgLoadingArray) {
if (each == 'false') {
loaded = false;
}
return loaded;
}
}
}
It seems to me that you just need an onload listener on the image that sets a value in an array or object. 在我看来,您只需要在图像上使用onload侦听器即可在数组或对象中设置一个值。 If each image has a unique name, then: 如果每个图像都有唯一的名称,则:
var imageLoaded = {};
...
'newImg': function(name) {
if (name) {
var img = new Image();
img.src = 'images/' + name + '.png';
img.name = name;
imageLoaded[name] = false;
img.onload = function() {imageLoaded[this.name] = true;};
...
}
},
...
Untested. 未经测试。
You can create a dictionary: 您可以创建一个字典:
var actions = [];
function createAction(name) {
actions[name] = function() {alert('Hi from:'+ name);};
}
createAction('hello world');
actions['hello world']();
I just realized... why have a variable at all? 我才意识到...为什么要一个变量呢? Just throw the whole thing into an object for loading! 只需将整个东西扔进一个要加载的对象中即可!
var resources = {
// load some other stuff
'newImg': function(name) {
if (name) {
game.resources.imgLoading[name] = new Image();
game.resources.imgLoading[name].src = 'images/' + name + '.png';
game.resources.imgLoadedCheck[name] = false;
game.resources.imgLoading[name].onload = function() {game.resources.imgLoadedCheck[name] = true;};
}
},
'imgLoading': {},
'imgLoadedCheck': {},
'loaded': function() {
var loaded = true;
for (each in game.resources.imgLoadingArray) {
if (each == 'false') {
loaded = false;
}
return loaded;
}
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.