Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tips for an intermediate javascript programmer to write better code

So I'm a fairly decent javascript programmer and I've just recently finished working on a fairly big web application that involved writing quite a bit of javascript. One of the things I can across when I was debugging my script was that there were some namespace conflicts with my various global variables I used throughout my script. Essentially, my javascript file was structured as such:

global var a
global var b
global var c
function1(){}
function2(){}
function3(){}

with a jQuery document on-ready function to bind various events to buttons in my html and call my functions as event handler callbacks.

Some people recommended encapsulating my entire script in one gigantic function to prevent any scope-related errors. I couldn't quite figure out exactly what that would entail. Any tips are appreciated as I am about to create another web app that will involve quite a bit of AJAX page loads to avoid browser refreshes and DOM manipulation bound to various events. Thanks!

like image 669
Casey Flynn Avatar asked Jul 01 '11 03:07

Casey Flynn


People also ask

How do I become an advanced JavaScript developer?

Earning a degree in computer science, one with a focus on software development is a strong qualification to have that can open up many programming job opportunities, including for JavaScript. A degree in software engineering or any other degree with a focus on coding is also a good option.


2 Answers

I recommend reading the jQuery plugin authoring guide (I also recommend you consider using jQuery if you are not)

http://docs.jquery.com/Plugins/Authoring

BTW this been asked many times (not a criticism for re-asking)

  • jQuery: Global Variable Namespace Problem
  • Avoiding polluting the global namespace with javascript dependencies
  • JavaScript Namespace

I also highly recommend you read about jQuery live plugin for register DOM events(I guess its built-in now): http://api.jquery.com/live/ (this will minimize the nasty need for state management of unbinding and rebinding your DOM nodes).

like image 180
Adam Gent Avatar answered Sep 23 '22 13:09

Adam Gent


A similar alternative to Michael's and nnnnnn's version is to do

var YourApp = {
    a: 1234,
    b: 5678,
    function1: function () {

    },
    etc
};

YourApp is the only global var and its properties can be accessed like

YourApp.function1();

or

YourApp.a;
like image 41
shelman Avatar answered Sep 26 '22 13:09

shelman