问题
I'm using a third party javascript that has given me a lot of need for listeners. For instance, when a certain div has been loaded, I want to do something with it. It changes styles of objects as it goes as well so I need to watch for it to have a certain style. I've build functions to act when an id or class exists. Here's the current ID function. As you can see, it uses jQuery.
function whenLoaded(element_id, action) {
if ($(element_id)) {
action();
}
else {
setTimeout("whenLoaded('"+element_ids+"',"+action+", '"+stop_on+"')", 500);
}
}
I really need something that I can give multiple conditions to. For instance:
whenTrue(
($('popup') && $('popup').style.width == '500px'),
$('popup').style.width = '0'
);
I would expect it to recursively check the conditions (1st param). When those conditions are true, perform the action.
I've been able to accomplish this using eval() but I have been warned not to use it, can't remember why. That being said, I'd like to accomplish this in another way.
eval() solution:
whenTrue(
"($('popup') && $('popup').style.width == '500px')",
"$('popup').style.width = '0'"
);
function whenTrue(condition, action) {
if (eval(condition)) {
eval(action);
}
else {
setTimeout("whenTrue('"+condition+"','"+action+"')", 500);
}
}
回答1:
function conditionListener(callback){
if(typeof callback !== 'function') return;
var interval, callback = callback;
interval = setInterval(function() {
if(true /* some condition */){
callback();
clearInterval(interval);
}
}, 500);
}
var listener = new conditionListener(function() {
/* ... do work ... */
});
http://jsfiddle.net/M26XS/
回答2:
I wrote this function once which looks like it does basically what you would want:
function pollUntilTrue(conditionFunc, afterTrueFunc, timeout) {
var __xinterval = setInterval(function() {
var res = conditionFunc();
if (res === true) {
clearInterval(__xinterval);
afterTrueFunc();
}
}, timeout);
}
you would use it with your code like this:
pollUntilTrue(function() {
return ($('popup') && $('popup').style.width == '500px');
},
function() {
$('popup').style.width = '0';
}, 500);
Adjust the timeout to suite your needs
回答3:
Why don't you just accept a condition and an action? that would make it much simpler.
function whenTrue(condition, action) {
if (condition) {
action();
}
else {
setTimeout("whenTrue('"+condition+"',"+action+", '"+stop_on+"')", 500);
}
}
and then you can provide the condition when calling the function, it would look like this:
whenTrue(($('popup') && $('popup').style.width == '500px') &&
$('popup').style.width === '0', someAction);
来源:https://stackoverflow.com/questions/9622639/how-do-i-create-a-javascript-listener-function-that-will-perform-an-action-when