I am trying to work on the chainability in a jquery plugin, and it works fine with jquery click below,
$(document).ready(function(){
$('.call-parent').parent_child({
target: '.element'
});
$('.call-child-1').click(function(){
$(this).parent_child().child_1();
return false;
});
$('.call-child-2').click(function(){
$(this).parent_child().child_2();
return false;
});
});
(function($) {
$.fn.extend({
parent_child: function(options) {
var defaults = {
target:''
}
var options = $.extend(defaults, options);
var o = options;
var $this = this;
var $cm = this.click(function(ei) {
alert('parent');
$this.child_1();
return false;
});
$this.child_1 = function() {
alert('child 1');
};
$this.child_2 = function() {
alert('child 2');
};
return $cm;
}
})
})(jQuery);
but I have the error when I use each or ready in the plugin, for instance,
$(document).ready(function(){
$('.call-parent').parent_child({
target: '.element'
});
$('.call-child-1').click(function(){
$(this).parent_child().child_1();
return false;
});
$('.call-child-2').click(function(){
$(this).parent_child().child_2();
return false;
});
});
(function($) {
$.fn.extend({
parent_child: function(options) {
var defaults = {
target:''
}
var options = $.extend(defaults, options);
var o = options;
var $this = this;
var $cm = this.each(function(ei) {
alert('parent');
$this.child_1();
return false;
});
$this.child_1 = function() {
alert('child 1');
};
$this.child_2 = function() {
alert('child 2');
};
return $cm;
}
})
})(jQuery);
error message,
$this.child_1 is not a function [Break On This Error]
Why can’t I do that with each or ready? Or have I done it wrong?
I’m restating my comment as an answer so you can accept:
Function expressions like
var f = function() { ... }do not get hoisted the way named function declarationsfunction f() { ... }do. So in theeachexample, setting$cmis calling$this.child_1before it has been declared. In your first example, the function is called on click, so it has already been parsed by the time it is executed.