简体   繁体   English

如何覆盖此jQuery插件的私有方法?

[英]How do I override this jQuery plugin's private method?

I was trying to override a method in this jQuery plugin which follows a "jQuery lightweight plugin boilerplate" pattern referenced in this Smashing Magazine article , however I seem to be missing something. 我试图覆盖此jQuery插件中的一个方法, 方法遵循此Smashing Magazine文章中引用的“ jQuery轻量级插件样板”模式,但是我似乎缺少一些东西。 [Edit: turns out the pattern intentionally makes the method private.] [编辑:证明模式是有意使方法私有的。]

$.fn.mbp exists when I test for it. $.fn.mbp在我测试时存在。 But when I use the following syntax to override one of its method, there is no error, and the plugin method is not overridden. 但是,当我使用以下语法重写其方法之一时,没有错误,并且未重写plugin方法。

$.fn.mbp.loadFiles = function() {
    alert('test')
};

As Tomalak said they the function is protected however it isn't out of reach. 正如Tomalak所说,它们的功能受到了保护,但并非遥不可及。
As it stores an instance of the mbp object in the jquery data storage we can grab the constructor of this object and overwrite the function. 由于它将mbp对象的实例存储在jquery数据存储中,因此我们可以获取此对象的构造函数并覆盖该函数。

From your code line 360: 从您的代码行360:

  $.fn[pluginName] = function ( options ) {
    return this.each(function () {
      if (!$.data(this, 'plugin_' + pluginName)) {
        $.data(this, 'plugin_' + pluginName,
          new MBP( this, options ));
      }
      else {
        if (options == 'options') {
          return $.data(this, 'plugin_' + pluginName).options;
        }
      }
    });
  }

Overwrite it: 覆盖它:

$.data( $('<div/>').mbp()[0], 'plugin_mbp').constructor.prototype.loadFiles = function() {
   // ...
}

However this is not really a very clean solution so you might think of another approach ;) 但是,这并不是一个很干净的解决方案,因此您可能会想到另一种方法;)

The plugin uses this appoach: 该插件使用以下方法:

(function ($) {
    function MBP() {
        // ...
    }
    MBP.prototype.loadFiles = function () {
        // ...
    };
    $.fn.mbp = function () {
        return this.each(function () {
            var mbp = new MBP();
            // ...
        });
    };
})(jQuery)

Bottom line: Due to the enclosing function, the MBP constructor is private. 底线:由于具有封闭功能,因此MBP构造函数是私有的。 You cannot modify it (at least not without modifying the source code of the plugin). 您不能修改它(至少在不修改插件源代码的情况下不能修改)。

You have to make sure that your code runs after the plugins code thus making sure it is overridden. 您必须确保您的代码在插件代码之后运行,从而确保其被覆盖。 One way of doing this is logging in your console another one is by using a break point and the testing if your code is hit before or after.Moreover I noticed that you are calling mbp while the function mentioned in your link is MBP .Notice the case difference.Hope it helps 一种方法是登录控制台,另一种方法是使用断点并测试代码是在代码之前还是之后被击中。此外,我注意到您在链接中提到的函数是MBP同时调用了mbp区分大小写。希望对您有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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