Questions about the "extendind jQuery" concept.
Hello, I'm starting developping my own jQuery plugins, and I'm loving
the jQUery way to do things, but now I need help to understand certain
concepts and standards the jQUery uadopts.
I'm trying to make a plugin to extend the jQuery object, to another
object... The main idea is to make something like:
$('#element').MyPluginName();
And $('#element') becomes ready to respond others methods, like:
$('#element').CustomMethod1();
$('#element').CustomMethod2();
But if a try to do $('#element2').CustomMethod1(); without $
('#element2').MyPluginName(); before, i should receive an error
message like: " $('#element2').CustomMethod1() is not a function "...
Reading some docs I got this plugin code:
jQuery.fn.MyPluginName = function() {
return this.each( function() {
this.EXTENDED1 = 'SOME COMPUTATION';
this.CustomMethod1 = function() {
alert('CustomMethod1');
};
this.CustomMethod2 = function() {
alert('CustomMethod1');
};
});
};
The reason to this approach is:
1) $('#element').MyPluginName() initializes a large amount of data in $
('#element') and it is required to the exection of all the adjacents
functions in this plugin. SO, it makes no sense to use the approach $
('#element').MyPluginName().CustomMethod1(); $
('#element').MyPluginName().CustomMethod2(); because it would be an
overhead...
But it does not work as expected:
$( function(){
$('ul#file_mannager1').MyPluginName();
$('ul#file_mannager1').each( function() { alert( this.EXTENDED1); });
$('ul#file_mannager1').each( function() { try{this.CustomMethod1();}
catch(a) { } });
$('ul#file_mannager1').each( function() { try{this.CustomMethod2();}
catch(a) { } });
// alert( $('ul#file_mannager1').EXTENDED1 ); undefined
// $('ul#file_mannager1').CustomMethod1(); ERROR
// $('ul#file_mannager1').CustomMethod2(); ERROR
//But with a default jQuery function, it works... on both
$('ul#file_mannager1').each( function() { alert( $(this).html()); });
alert( $('ul#file_mannager1').html() );
});
How can I solve this???