繁体   English   中英

如何在不影响此参数的情况下将参数绑定到jQuery回调

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM