I'm writing a jQuery plugin, and I want to attach that plugin to the selected element only when it is present, without having any click or other events.
This plugin has it other chained functions and I want to call this functions when this plugin is attached to that element.
And I want to pass that element as an object into the chained functions.
But I get this error message and the plugin does not work of course! I get the same error whether I use each
or ready
in that plugin
return this.each(function() {...}
return this.ready(function() {...)
TypeError: $this.function_1 is not a function
How do I make it right?
jquery,
$(document).ready(function(){
$('.box').selection();
});
(function($){
$.fn.extend({
selection: function(options) {
var defaults = {
element: "selection"
}
var options = $.extend(defaults, options);
var o = options;
// Must declare a this variable outside the core if you have other children functions inside this plugin.
var $this = this;
return this.each(function() {
// Set the object.
var object = $(this);
//alert(object.html());
// Attach the functions.
$this.function_1(object);
$this.function_2(object);
});
// function_1
$this.function_1 = function(object)
{
alert('function 1');
}
// function_2
$this.function_2 = function(object)
{
alert('function 2');
}
}
});
})(jQuery);
html,
<div class="box">
<ul class="selection">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>
at jsfiddle
You are calling return
before declaring the functions. Move the function declarations above the call to return
and it works.