Note that there are some explanatory texts on larger screens.

plurals
  1. POjQuery plugin bind issue
    text
    copied!<p>This question refers to my previous question (<a href="https://stackoverflow.com/questions/15163082/jquery-plugin-click-instance-issue-design-pattern-feedback">jQuery plugin click instance issue &amp; design pattern feedback</a>). My previous question focuses more on the design approach I use. </p> <p>I want to bind click events to the element I invoked the script on:</p> <p>main.js</p> <pre><code>$('nav ul li a.has-sub').sidebarNav(); </code></pre> <p>The problem with toggle: <strong>self doesn't return the actual instance, but always the last instance</strong> - How to resolve this?</p> <pre><code>toggle : function(){ console.log(self); // Should return the right instance, but it doesn't! } </code></pre> <p>In my plugin:</p> <pre><code>_bindEvents : function(){ self.$elem.bind('click.sidebarNav', self.toggle); }, </code></pre> <p>jquery.sidebarNav.js</p> <pre><code>;(function($){ "use strict"; var SidebarNav = function(element, options){ this._init(element, options); } SidebarNav.prototype = { _init : function(element, options){ var self = this; self.elem = element; self.$elem = $(element); self.options = $.extend( {}, $.fn.sidebarNav.defaults, options); self._bindEvents(); }, _bindEvents : function(){ self.$elem.bind('click.sidebarNav', self.toggle); }, toggle : function(){ console.log(self); } } $.fn.sidebarNav = function(options) { return this.each(function(){ var instance = new SidebarNav(this, options); $.data(this, 'sidebarNav', instance); }); } $.fn.sidebarNav.defaults = {} })(jQuery); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload