gpt4 book ai didi

javascript - 在没有 eventData 的情况下通过 jQuery 事件调用传递匿名函数

转载 作者:行者123 更新时间:2023-11-29 16:07:17 25 4
gpt4 key购买 nike

给定一个 <input id="foo">元素,我想在 blur 上调用一个现有的函数,并向它传递一个匿名回调。

案例一,简单的函数调用:

function bar(){
alert("I am");
}

$("#foo").blur(bar); //Works fine

案例 2,传递参数/函数:

$("#foo").bind("blur", {func: function(){console.log("I am apple")}}, bar);

function bar(event){
event.data.func(); //Works fine
};

案例 2 的问题是我想要 bar()作为由 more than blur 调用的通用函数,在这种情况下,我将直接传递匿名函数,而不是“烘焙”到数据对象中。理想情况下是这样的:

function bar(callback){
//Do stuff
callback();
}

bar(function(){console.log("Hello Earth")}); //Works

$("#foo").blur(bar(function(){console.log("Hello world")})); //Doesn't work

最后一行不起作用,因为函数直接执行,但它是我想要实现的示例。我想我可能可以在 bar() 中进行一些类型检查确定我收到的是什么,但我想问一下是否有更简洁的方法在模糊上传递匿名函数,而不是更改 bar() .

最佳答案

...I wanted to ask if there's a cleaner way to pass anonymous function on blur, instead of changing bar().

不太确定您的意思,您将不得不更改 bar 或换行 bar

改变它:

使 bar 成为处理程序 generator 而不是直接处理程序:

function bar(callback) {
return function(e) {
// You could use `e` (the event) here and/or pass it on to the callback
callback();
// You might use the callback's return, e.g.:
// return callback();
// ...if you wanted it to be able to `return false`
};
}

现在,bar 返回一个将调用回调的事件处理程序(此外,大概是做它自己的事情;否则,它有点毫无意义,您只需直接传递回调).

用法:

$("#foo").blur(bar(function(){console.log("Hello world")}));

包装

如果您的字面意思是您不想更改栏,则需要包装它:

function wrap(f, callback) {
return function() {
// You could call `callback` here instead of later if you like

// Call the original function passing along the `this` and
// arguments we received (`arguments` isn't pseudo-code, it's
// a pseudo-array JavaScript creates for you), get its return value
var retval = f.apply(this, arguments);

// Call the callback
callback();

// Return the original function's return value
return retval;
};
}

如果你想避免让callback抛出的错误进入事件机制,你可以将它包装在一个try/catch.

用法:

$("#foo").blur(wrap(bar, function(){console.log("Hello world")}));

关于javascript - 在没有 eventData 的情况下通过 jQuery 事件调用传递匿名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38054276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com