[英]How do I test for the result of a regular expression in a switch in JavaScript
[英]How do I send a condition test to a Javascript function and not only it's result?
我想到了制作一個小型jQuery插件的想法,但是有些事情我不得不依靠eval
不知道如何做。
這是代碼:
var testMe = 1;
$.extend({
once : function( condition, duration, callback) {
window[ "once" ] = window.setTimeout(function() {
if ( condition )
{
callback.apply();
window.clearTimeout( window[ "once" ] );
} else {
window[ "once" ] = window.setTimeout( arguments.callee, duration * 1000 );
}
}, duration * 1000 );
}
});
$.once(testMe == 2, 5, function() {
alert("Match!");
});
看起來像在調用$.once()
,然后對第一個參數求值,並且此時僅將其值發送到condition參數。 我發現的唯一方法是將其作為字符串發送:
$.once("testMe == 2" ...
並使用if ( eval( condition ) )
使用eval
是否還有另一種方法?
謝謝。
編輯:這是插件的最終版本:
var testOne = 1,
testTwo = 1;
$.extend({
once : function( name, conditionFn, duration, callback) {
if ( typeof duration == "function" )
{
callback = duration;
duration = 5;
}
window[ "once" + name ] = window.setInterval(function() {
if ( conditionFn() )
{
callback();
window.clearInterval( window[ "once" + name ] );
}
}, duration * 1000 );
}
});
//Examples
$.once("testOne", function() {
return testOne == 2
}, 2, function() {
alert("testOne == 1");
});
$.once("testTwo", function() {
return testTwo == 2
}, 2, function() {
alert("testTwo == 1");
});
你是對的; 評估參數,然后傳遞。 我不建議您使用eval
除非您真的知道自己在做什么,並且有充分的理由這樣做。
而是將一個謂詞 (一個返回布爾值的函數)傳遞給您的插件。 每次要進行檢查時,請調用以下函數:
var testMe = 1;
$.extend({
once : function(predicate, duration, callback) {
window.once = window.setInterval(function() {
if (predicate()) {
window.clearInterval(window.once);
callback();
}
}, duration * 1000);
}
});
$.once(function () { return testMe == 2; }, 5, function() {
alert("Match!");
});
注意,我用自取消setInterval()
代替了重復的setTimeout
調用。 另外,您正在使用callback.apply()
調用callback
,但是沒有理由這樣做。 您可以使用()
直接調用它,就像上面的代碼一樣。
發送一個返回比較結果的函數:
var testMe = 1;
$.extend({
// receive the function
once : function( conditionFn, duration, callback) {
window[ "once" ] = window.setTimeout(function() {
// execute the function
if ( conditionFn() )
{
callback.apply();
window.clearTimeout( window[ "once" ] );
} else {
window[ "once" ] = window.setTimeout( arguments.callee, duration * 1000 );
}
}, duration * 1000 );
}
});
// send a function
$.once(function(){return testMe == 2;}, 5, function() {
alert("Match!");
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.