Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a good structure for my jQuery scripts?

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?

like image 624
jsn00bs Avatar asked Sep 22 '11 20:09

jsn00bs


People also ask

Is jQuery still recommended?

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.

Is jQuery harder than JavaScript?

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.

Why should we write a well structured JavaScript code?

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.


1 Answers

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.

like image 137
g.d.d.c Avatar answered Sep 20 '22 20:09

g.d.d.c