Reputation: 1427
I am trying to understand the difference between the following two sets of code. When I use the jquery plugin definition, I am able to access the plugin outside of a self enclosed function. However, if I attempt to simply setup some objects with the same self enclosed function, it does not work.
This works:
(function($) {
$.fn.test = function(message) {
return this.each(function() {
$(this).text(message);
});
}
}(jQuery));
$(document).ready( function() {
$('p').test('This works!');
});
Does Not Work:
(function($) {
var neato={
start:function(){
$('p').html('We must have an issue of scope or similar, this does not work');
}
}
}(jQuery));
$(document).ready(neato.start);
Is there a way to make my object available outside of the self enclosed function in this case?
Upvotes: 0
Views: 111
Reputation: 2690
The whole purpose of putting the code inside the IIFE was to ensure that outside code cannot access the variables inside of it. If you want to access it, you will have to attach it to a variable declared outside of that function scope, so in your example, the global $
object. Alternatively, you can attach it to window:
(function ($) { ...
....
window.neato = neato;
})(jQuery);
$(document).ready(neato.start);
Upvotes: 5