簡體   English   中英

JQuery 等效於 MooTools 綁定(此)

[英]JQuery equivalent of MooTools bind(this)

我正在嘗試使用此class 插件在 JQuery 中重寫 Mootools 工具提示 class 。 當我的 class 被實例化時,我將一個事件監聽器附加到一個目標鏈接,這將淡出工具提示。

在事件回調中 JQuery 將關鍵字“this”分配給事件的目標,因此為了保持對 class 屬性的引用,我使用apply()將“this”設置為表示 ZA2F2ED4F8EBC2CBB1C21A29DC40 實例。 這顯然是 Mootools 的方便bind() function 的 JQuery 中的對應物。

不幸的是,當我使用apply()時,我丟失了回調的事件參數。 例如,在這個位中,我在第二行收到“e is undefined”錯誤。

this.target.bind('click', function(e){
    e.preventDefault();
    var tip = this.opts.tip;
    tip.fadeOut(500, function(){
        tip.bind('click', function(){
            showing = false;
        })
    });
}.apply(this))

我在這里錯過了一個技巧嗎? 有人知道解決這個問題的方法嗎?

TBH,你所說的mootools .bind只是 ES5 中的Function.bind - 並且在支持 js 1.8.5 + 規范的瀏覽器中原生可用。 MooTools 只是增強了還沒有它的瀏覽器,但讓原生實現保留在原型上——如果可用的話。

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind

如果本機不可用,您可以輕松地將其實現為Function.prototype.bind裝飾器,並按照上面的示例使用它:

// Function.prototype.bind polyfill
if ( !Function.prototype.bind ) {

  Function.prototype.bind = function( obj ) {
    if(typeof this !== 'function') // closest thing possible to the ECMAScript 5 internal IsCallable function
      throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');

    var slice = [].slice,
        args = slice.call(arguments, 1), 
        self = this, 
        nop = function () {}, 
        bound = function () {
          return self.apply( this instanceof nop ? this : ( obj || {} ), 
                              args.concat( slice.call(arguments) ) );    
        };

    bound.prototype = this.prototype;

    return bound;
  };
}

如您所見,它比簡單的.apply / .call更復雜一些

要考慮的一件事是,如果您需要使用 bind 或者您是否可以保存引用。

例如。

var self = this;
this.target.bind("click", function(e) {
    var tip = self.opts.tip;
});

無論如何,這比 function 綁定的占用空間更小。 它還為您提供了正確引用this作為觸發元素( event.target === this )。 您會在 mootools-core 中發現這種模式比綁定模式更常見 - 盡管當您想將事件分配給 class 方法時通常需要綁定,例如:

this.element.addEvents({
    click: this.showTip.bind(this),
    mouseleave: this.hideTip.bind(this)
});

在這種情況下,保存引用將不起作用,盡管您可以將其重寫為

var self = this;
this.element.addEvents({
    click: function(e) {
        self.showTip(e);
    }
});

jQuery 的特定實現是proxy - http://api.jquery.com/jquery.proxy/

在某個元素上發生的所有事件(例如,“點擊”就是其中之一)應該有一個指向該元素的目標屬性

var $this = $(e.target); // $this will be the clicked element

JSFiddle

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM