2015-11-06 20 views
0

我正在創建一個jQuery插件,並且我需要讓它響應窗口大小調整事件。我遇到的問題是,如果你只有一個插件實例,但是如果只有更多的實例只有後者可以工作,它才能正常工作。我的插件代碼看起來像如何將窗口大小調整事件綁定到插件實例

(function ($) { 

    //Define it 
    var MyPlugin = function (element, options) { 
     //... 
    }; 

    MyPlugin.prototype.init = function() { 
     $that = this; 
     $(window).bind('resize',function(e) { 
      //This only seems to get called for the last instance of the plugin 
      $that.recalculate(); 
     }); 
    } 

    MyPlugin.prototype.recalculate = function() { 
    } 

    $.fn.myPlugin = function (option) { 
     return this.each(function() { 
      var $this = $(this); 
      var options = typeof(option) === 'object' ? option : {}; 
      new MyPlugin(this, options)); 
     }); 
    }; 
}(jQuery)); 

的問題是,窗口大小調整事件不會調用該插件的每個實例,所以如果我有兩個實例,像這樣,只有div2會工作。

$('.div1').myPlugin(); 
$('.div2').myPlugin(); 
+0

,又是什麼大小調整處理呢? (你假設只有最後一個處理程序被調用幾乎肯定是錯的) – Amit

+0

@Amit我更新了代碼以使它更清晰 – Pattle

回答

-1

嘗試使用下面的代碼

$.fn.myPlugin = function (option) { 
    var options = typeof(option) === 'object' ? option : {}; 
    return new MyPlugin(this, options); 
}; 
0

我覺得沒有辦法執行窗口調整多次,每個實例來改變你的代碼。 試圖創建全局數組來存儲實例,並在調整大小時恢復它。

var instances = [] ; 

(function ($) { 

    //Define it 
    var MyPlugin = function (element, options) { 
     instances.push(this); 
     this.element = element; 
     this.init(); 
    }; 

    MyPlugin.prototype.init = function() { 
     $that = this; 
     $(window).bind('resize',function(e) { 
      $that.recalculate(); 
     }); 
    } 

    MyPlugin.prototype.recalculate = function() { 
     for(i in instances) 
      console.log('recalculate', instances[i].element.html()); 
    } 

    $.fn.myPlugin = function (option) { 
     var options = typeof(option) === 'object' ? option : {}; 
     return new MyPlugin(this, options); 
    }; 
}(jQuery)); 

$('.div1').myPlugin(); 
$('.div2').myPlugin(); 

看到的`$ that`定義的例子https://jsfiddle.net/kbggthb0/5/

相關問題