Reputation: 63
Ok, so I a have a module called "SelectorsModule". In it, I have an object literal which will contain all the jQuery selectors that will be used within the application during various user interactions (see below)
In order to stop from repeating the same $(selector) code each time the selector is used, I thought it would be more efficient to place all shared selector elements into its own 'SelectorsModule'. This way, if any changes need to be made, it only needs to be modified in one place and everything would still work. Each selector could also then be called from a single place, ie. "SelectorsModule.getSelectors.selectorTwo", for example.
var SelectorsModule = SelectorsModule || {};
SelectorsModule = (function(){
// Private methods and variables
var sharedSelectors = {
selectorOne: $("#element-one"),
selectorTwo: $("#element-two"),
selectorThree: $("#element-three"),
selectorFour: $("#element-four")
};
// Public methods and variables
return{
getSelectors: function(){
return sharedSelectors;
}
};
})();
My questions:
Each time I use SelectorsModule.getSelectors.selectorOne
in my code now (to obtain the jQuery selector object), am I simply referencing the single instance of the SelectorsModule
, created when the script is first run, or is a new SelectorsModule
'object', created behind the scenes each time? The latter would obviously perform a lot worse and just need some clarification really?
Is my current approach WRONG, FLAWED, OK, GOOD, PERFECTLY FINE or SPOT ON?
Upvotes: 0
Views: 59
Reputation: 1696
(1) Each time you call
SelectorsModule.getSelectors().selectorOne // note the parentheses for invocation
you are accessing the same singleton object that you created when the code first ran.
(2) I would say that it is OK but I would have two concerns:
(a) do these selectors belong together in a separate object, or do some apply to some objects/pieces of behaviour and others to other areas? This is purely opinion, but they might be better encapsulated within the objects that act upon them.
(b) bear in mind that the jQuery function only gets called once for each selector, at the time of instantiation of your SelectorsModule. This means that, if you were to modify the DOM after instantiating the module, any changes would not be reflected in the jQuery objects returned by the module's properties.
Lastly, as a side note, using the term 'selector' in the property names would be a bit confusing (although I suspect that this is only for the purposes of the question). The string that is passed to the jQuery function is a 'selector', but the properties themselves each contain 'a jQuery object' and not strictly speaking a selector.
Upvotes: 0
Reputation: 33409
1) You use the same instance of the module created originally.
2) It seems perfectly fine to me.
Upvotes: 1