I am using JQuery in a Module Pattern. I have a question about using JQuery Objects.
See the following example:
var myFeature = {
'config' : {
'container' : $('#myFeature'),
'init' : function(config) {
myFeature.config.container.css('display', 'none');
}
}`
Why does the above example not work? What would be best practice when working with Jquery Objects in module pattern?
Assuming that I've added the missing }
in the right place (I also added a semicolon at the end, I don't recommend relying on the horror that is Automatic Semicolon Insertion):
var myFeature = {
'config' : {
'container' : $('#myFeature'),
}
'init' : function(config) {
myFeature.config.container.css('display', 'none');
}
};
...then the only reason I can see for why it wouldn't work would be if this code were executed before the element existed. So your container
property ends up referring to a jQuery set with nothing in it, because as of when that property was initialized, there was no element with the id
"myFeature"
.
The solution would be to initialize the container
property at a time when you know the element exists, or to not use the container
property at all since looking up an element by its id
is very, very fast.
If the element is in the main markup of your page, make sure that the script
tag that contains the code above is after that markup. The usual recommendation is to put the script
tag(s) at the very end of your page, just before the closing </body>
tag, so that all elements in the page's markup exist as of when the script code runs.