I've built a jQuery plug-in and I'm struggling to understand why I can call a "public" method in one case, but not the other. I've tried to strip the plug-in down to bare bones for readability. Why can I call them method when the object is returned from an .each() loop or from within the .click() function, but not when I find the object directly and call the method? See below.
A fiddle is at http://jsfiddle.net/SSuya/
<script>
// ====================================
// My Reusable Object:
// ====================================
;(function ( $, window, document, undefined ) {
var pluginName = "ToolTip",
defaults = {
foo: 'bar',
};
function Plugin( element, options ) {
var widget = this;
this.element = element;
this.options = $.extend( {}, defaults, options );
this._defaults = defaults;
this._name = pluginName;
this.element.ToolTip = this;
this.init();
}
Plugin.prototype = {
init: function() {
alert("I'm ready!");
},
hideTip: function() {
alert("I'm hiding!");
},
showTip: function() {
alert("I'm showing!");
}
};
// A really lightweight plugin wrapper around the constructor,
// preventing against multiple instantiations
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName, new Plugin( this, options ));
}
});
};
})( jQuery, window, document );
</script>
<html>
<body>
<div id='tip-test'>Target me!</div>
<input id='bad-button' type="button" onclick="badCode()" value="This won't work...">
<input id='good-button' type="button" onclick="goodCode()" value="But this will...?">
</body>
</html>
<script>
$("#tip-test").ToolTip(); // Works fine.
$("#bad-button").click(function(){
$("#tip-test").ToolTip.showTip(); // This will generate an error
});
$("#good-button").click(function(){
$("#tip-test").each(function(){
this.ToolTip.showTip(); // Will work just fine...
});
});
</script>