[英]How to bind an argument to a jquery callback without affecting this
我是javascript / jquery的新手,这是我需要帮助的示例代码:
function add(text) { $(this).replaceWith('<label>'+text+'</label>'); } var label = 'Added'; $('#myDiv').append($('<button type="button">Add</button>').click(function() { add.call(this, label); }));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="myDiv"></div>
在这里设置click
回调的“更好”方法吗?
如果加载项功能没有一个text
的说法,我可以很容易使用.click(add)
,按钮就会自动绑定this
。
但是有了这个参数,我不能绑定text
而不必设置this
的值,即.click(add.bind(this, label))
将是错误的,因为this
是设置为全局上下文的。
思考?
正如Andreas在评论中指出的那样,有一个针对jQuery事件处理程序的解决方案: on
函数的data
参数。
不过,更笼统地说,您所寻找的内容有时被称为“咖喱”(或“部分申请”;纯粹主义者告诉我,其中之一在技术上是不正确的,但我永远都记不清)。
我有一个函数,用于添加到Function.prototype
; 它看起来像这样(请参阅评论) :
(function() {
var slice = Array.prototype.slice;
Object.defineProperty(Function.prototype, "curry", {
value: function() {
// Remember the original function and the arguments we wre called with
var f = this,
curried = slice.call(arguments);
// Return a new function
return function() {
// Our function was called, add in any arguments it was called with...
var args = curried.concat(slice.call(arguments));
// ...and call the original, passing along `this`
return f.apply(this, args);
};
}
});
})();
在您的情况下,可以这样使用它:
var label = 'Added';
$('#myDiv').append($('<button type="button">Add</button>').click(add.curry(label)));
请注意,您的add
函数将使用label
的值进行调用(就像我们进行curry
调用时那样,而不是后来的情况),然后是调用了curried函数的所有参数(例如,事件对象)。
例:
(function() { var slice = Array.prototype.slice; Object.defineProperty(Function.prototype, "curry", { value: function() { // Remember the original function and the arguments we wre called with var f = this, curried = slice.call(arguments); // Return a new function return function() { // Our function was called, add in any arguments it was called with... var args = curried.concat(slice.call(arguments)); // ...and call the original, passing along `this` return f.apply(this, args); }; } }); })(); function add(text) { console.log("add called with text = '" + text + "'"); } var label = 'Added'; $('#myDiv').append($('<button type="button">Add</button>').click(add.curry(label)));
<div id="myDiv"></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.