覆盖jQuery插件的init函数

时间:2018-11-01 11:24:52

标签: jquery jquery-plugins override

我想覆盖jquery插件的init函数以及该插件的自定义函数(例如html)。但是没有任何效果。这是我的代码

谢谢。

(function(jQuery) {
  jQuery.mainplugin = function(element, options) {
    var defaults = {};

    this.init = function() {
      this.settings = jQuery.extend({}, defaults, options);
      alert('main')
      // more code here
    };

    this.html = function() {
      // main code here 
    }

    this.init();
  };

  jQuery.fn.mainplugin = function(options) {
    return this.each(function() {
      if (undefined == jQuery(this).data('mainplugin')) {
        var plugin = new jQuery.mainplugin(this, options);
        jQuery(this).data('mainplugin', plugin);
      }
    });
  };
})(jQuery);

这是我要覆盖的代码:

$(document).ready(function($) {
  $.fn.mainplugin.init = function() {
    alert('override')
  }

  $.fn.mainplugin.html = function() {
    alert('override')
  }

  $(".is-wrapper").mainplugin();
});

1 个答案:

答案 0 :(得分:1)

不是通过“覆盖”功能,而是通过options对象将它们传递给插件:

(function($) {
  $.mainplugin = function(element, options) {
    var settings = $.extend({
      init: null,
      html: null
    }, options);

    this.init = settings.init || function() {
      console.log('main')
    };

    this.html = settings.html || function() {
      console.log('html');
    }

    this.init();
  };

  $.fn.mainplugin = function(options) {
    return this.each(function() {
      if (undefined == $(this).data('mainplugin')) {
        var plugin = new $.mainplugin(this, options);
        $(this).data('mainplugin', plugin);
      }
    });
  };
})(jQuery);

$(document).ready(function($) {
  // plain
  $('.foo').mainplugin().data('mainplugin').html();

  // overridden
  $(".is-wrapper").mainplugin({
    init: function() {
      console.log('init override');
    },
    html: function() {
      console.log('html override');
    }
  }).data('mainplugin').html();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo"></div>
<div class="is-wrapper"></div>