I want to keep my scripts organized in one .js file for all my site (I have a mess right now), something like namespaces and classes in C#...
(function ($) {
//private variables
$.divref = $("#divReference");
//Namespaces
window.MySite = {};
window.MySite.Home = {};
window.MySite.Contact = {};
//Public function / method
window.MySite.Home.Init = function(params){
alert("Init");
MySite.Home.PrivateFunction();
$.divref.click(function(){
alert("click");
});
};
//private function / method
MySite.Home.PrivateFunction = function(){
alert("Private");
};
})(jQuery);
Is this an idiomatic layout in jQuery and JScript?
It's good to know jQuery and there are still use cases for it. However, you should not spend a lot of time learning it. jQuery should not be your focus this year. The biggest advantage of jQuery now is that you can manipulate the DOM with less code.
Therefore developers find it easier to work with jQuery than with JavaScript. Though JavaScript is the basic language from which jQuery has evolved, jQuery makes event handling, DOM manipulation, Ajax calls much easier than JavaScript.
Keep Code Organized Our JavaScript code should be organized well so that they can be easily reasoned with. Well organized code don't repeat anything. Functions and classes inside all do one thing only and no more.
I'll go ahead and post my comment as an answer, though I'm not 100% it addresses your questions about c# namespaces and their parallels in JavaScript (I'm no c# programmer). You're not actually creating private variables because you're attaching them to the $
Object that will exist after this function finishes. If you want private variables you need to use a closure. Those look something like this:
var myObject = function () {
var innerVariable = 'some private value';
return {
getter: function () {
return innerVariable;
}
}
}()
If you attempt to access myObject.innerVariable
it will return undefined
but if you call myObject.getter()
it will return the value correctly. This concept is one you will want to read up on in JavaScript, and for programming in general. Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With