[英]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.