2015-11-06 88 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/

相关问题