jQuery插件对象:通过.on()附加一个事件处理程序,现在有一个范围问题。 (主插件对象)

我试图摆脱我的jQuery插件中的意大利面条代码,并以更有条理的方式工作。

我这样做是通过使用这里找到的基本样板模板: https : //github.com/jquery-boilerplate/jquery-patterns/blob/master/patterns/jquery.basic.plugin-boilerplate.js

我还发现ToDo MVC普通jQuery代码是灵感的源泉,因为它没有链接许多function并且保持很好的分离(由于我缺乏状态,我不允许发布两个以上的链接,因此你必须使用Google那个你自己)。

总而言之,我发现上面两者的组合非常适合使用,但似乎没有办法像这样工作而不经常引用this (根插件对象)。 这本身不是问题,但有时this会超出范围。 我还没有真正找到一种优雅的方法,特别是在通过jQuery绑定事件处理程序on.() 。 请看我的JSFiddle,说明我的意思: http : //jsfiddle.net/hendrikdegraaf/wzp3ok4h/18/

我发现将event.data对象中的插件对象作为event.data.base有点尴尬(它只是非常冗长并且损害了我的代码的可读性)。 有没有更好的方法来引用主插件对象?

在使用这种构造我的插件的方式之前,我遇到了变量范围的问题,所以关于如何以合理的方式构建我的插件的任何一般建议也将受到赞赏。

谢谢,
亨德里克

编辑:请参阅下面的代码

 ;(function ( $, window, document, undefined ) { // Create the defaults once var pluginName = "myplugin", defaults = { settingA : 'someValue', settingB : 'someValue' }; // The actual plugin constructor function Plugin(params) { params.options = $.extend( {}, defaults, params.options); this.params = params; this._defaults = defaults; this._name = pluginName; this.init(); } Plugin.prototype = { init: function () { var base = this; // cache the context so we can still reference it when entering new context this.cacheElements(); this.bindEvents(base); }, cacheElements : function (base) { //cache elements this.$el = $('div.doSomething'); }, bindEvents : function (base) { // bind some touch functions to touch events, and modal window hidden event this.$el.on('click', {base: base}, this.myFunction); }, myFunction : function () { console.log(this); //this now refers to $el } }; // A really lightweight plugin wrapper around the constructor, // preventing against multiple instantiations $.fn[pluginName] = function ( params ) { return this.each(function () { if (!$.data(this, "plugin_" + pluginName)) { $.data(this, "plugin_" + pluginName, new Plugin(params)); } }); }; })( jQuery, window, document ); 

我最近遇到了这个问题,我发现了一些解决方法。

JavaScript的bind适用于现代浏览器:

 bindEvents : function (base) { this.$el.on('click', {base: base}, this.myFunction.bind(this)); }, myFunction : function () { console.log(this); // Plugin context } 

jQuery的proxyfunction适用于旧版浏览器:

 bindEvents : function (base) { this.$el.on('click', {base: base}, $.proxy(this.myFunction, this)); }, myFunction : function () { console.log(this); // Plugin context } 

您还可以在bindEvents函数中创建事件处理函数,并允许自己访问这两个上下文:

 bindEvents : function (base) { var instance = this; var myFunction = function() { console.log(this); // element context console.log(instance); // Plugin context }; this.$el.on('click', {base: base}, myFunction); }