Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Recently, I've noticed that my code looks so ugly because there were a bunch of functions and global variables. So, I started reading a little bit about design patterns. Now I come with something that's working for me, but I am not sure if it's good practice.

Anyway, I would like you to take a look at the code and tell me what can I improve. I'd also like to know a better way to start using modular pattern in JavaScript. Finally, I'd like suggestions on material for learning about modular pattern and JavaScript.

var responsiveModule = {

    settings: {
        device: false,
        button: $(".responsive-btn"),
        target: $("nav ul"),
        mobileClass: "toggle-menu",
        bgImage: '<img class="background-image" src="img/background.jpg" alt="">',
        bgImageSelector: $(".background-image"),
        windowWidth: $(window).width(),

    },

    init: function(){
        responsiveModule.checkDevice();
        responsiveModule.replaceImages();
        responsiveModule.bindFunctions();
        responsiveModule.listenResize();
    },

    checkDevice: function(){
        if(this.settings.windowWidth > 992){
            this.settings.device = "desktop";

        } else {
            this.settings.device = "mobile";
        }
    },

    bindFunctions: function(){
        var buton = this.settings.button,
            muelleBtn = this.settings.muelleBtn;
        buton.on("click touchstart", function(e){
            e.preventDefault();
            responsiveModule.animateMenu(responsiveModule.settings);
        });
    },

    animateMenu: function(settings){
        var device = settings.device,
            target = settings.target,
            mobileAnimation = settings. mobileClass;

        if(device == "mobile"){
            target.toggleClass(mobileAnimation);
        }
    },

    replaceImages: function(){
        var bgContainer = $("#main-content"),
            bgImage = responsiveModule.settings.bgImage,
            device = responsiveModule.settings.device,
            backgroundSelector = $(".background-image");

        if(device == "desktop" && backgroundSelector.length == 0){
            bgContainer.append(bgImage);
        }else if(device == "mobile" && backgroundSelector.length == 1){
            backgroundSelector.remove();
        }
    },

    listenResize: function(){
        $(window).on("resize", function(){
            responsiveModule.checkDevice();
            responsiveModule.replaceImages();
            responsiveModule.settings.windowWidth = $(window).width();
        });
    }


}

var tooltipModule = {

    settings: {
        tooltipState: false
    },

    init: function(){
        tooltipModule.bindUIfunctions();
    },

    bindUIfunctions: function(){
        var device = responsiveModule.settings.device;
        if(device == "mobile"){
            $(".ship").on("click", function(e){
                e.preventDefault();
                tooltipModule.manageTooltip(e);
            });
        }else{
            $(".muelle-item").addClass("desktop");
        }
    },

    manageTooltip: function(e){
        var tooltip = $(e.currentTarget).next(),
            tooltips = $(".tooltip");

        tooltips.removeClass("display");
        tooltip.addClass("display");
    }


}


$(document).on("ready", function(){
    responsiveModule.init();
    tooltipModule.init();   
});
share|improve this question
6  
Contrary to some of the answers below, note that a lot of people define prototypes as a form of OOP stackoverflow.com/questions/186244/… –  Stuart Sep 3 '13 at 15:31

3 Answers 3

The best pattern to start "OOP" in JavaScript is the Revealing Pattern:

var revealed = function(){
   var a = [1,2,3];
   var abc = function(){
     return (a[0]*a[1])+a[2];
   }

   return {
      name: 'revealed',
      abcfn: abc
   }
}();

From here.

Then read this book.

And learn RequireJS, which will increase the modularity of your code and will load your JS files on demand.

I see you are using JS for create HTML elements. To help you with this, take a look at UnderscoreJS templates and Mustache.

share|improve this answer
2  
That “revealing pattern” is not related to OOP. –  icktoofay Sep 3 '13 at 0:44
    
why not, don't is encapsulation the key concept of OOP? –  Claudio Santos Sep 3 '13 at 2:06
1  
@Claudio: Object-oriented programming centers around objects, usually with functionality attached. I'll admit that that “revealing pattern” does create an object, but it's only one, ever, and that one object only functions as a set of namespaced variables, and I don't think that utilizing an object for that purpose counts as object-oriented programming. –  icktoofay Sep 3 '13 at 5:30
1  
@icktoofay here you can see an example of inheritance. –  Claudio Santos Sep 4 '13 at 12:17
1  
Requirejs doesn't increase modularity, per se... you don't even have to learn to use it, just learn to require scripts on-the-fly... it's not that hard –  Elias Van Ootegem Sep 4 '13 at 15:39

Don't, just don't.

JavaScript is not an OO language, it is a prototype language, something a lot of people tend to forget.

There are no 'classes' or 'interfaces' in javascript. Everything is an object. Even a function is an object.

So how do JavaScript Objects work? what is 'this'? and what does 'new' do? A good place to start is understanding Scope and context.

So, what are JavaScript objects? Again there is a good article.

Once you understand that and you still feel like writing OO Js. There are tons of frameworks out there that pretend to be OO, my personal favorite MooTools. These frameworks give you an interface to write OO-like code. But then again, in big applications that code tends to get slow, leak memory, since we forget how prototypes really work and what the 'new' operator means.


Let's recap and go back to your question. Your real problem is that your code is becoming hard to read.

So you are looking for a certain pattern in JavaScript to help in maintaining your code. My favorite pattern is the Module Pattern, but there are many more very strong patterns for JavaScript.

share|improve this answer
    
wow thank you for the awesome answer, I am going to read all the resources you post it in order to understand better the language!!! –  Jhonnatan Gonzalez Rodriguez Sep 3 '13 at 13:58
5  
-1 for saying that JavaScript isn't Object-Oriented and then stressing how everything in JavaScript is an object. Can you spot the contradiction? If I could -1 you again for recommending Adnan's book, I would; It's a waffly rehash of things Adnan has read else where and doesn't understand. –  itsbruce Sep 3 '13 at 15:40
1  
Object-oriented and everything is an object is not contradictory... Object-oriented design pattersn need abstract classes, interfaces,... these don't exist in javascript. Simply because everything is an object. In javascript there is no inheritance chain, but prototypes. –  Pinoniq Sep 3 '13 at 15:45
1  
@JhonnatanGonzalezRodriguez My usual recommendation for people new to JavaScript is to start with Douglas Crockford's website and his book, JavaScript: The Good Parts. javascript.crockford.com Looking at your code, I think you need to get a better feel for the basics of the language before reaching for larger patterns. Patterns are overused, mostly by people who don't understand their language of choice well enough to know where they are truly appropriate. –  itsbruce Sep 3 '13 at 16:12
3  
@Pinoniq javascript not only has object oriented capability, it has strong object oriented capability. Yes, it is a prototype based programming and that is in turn a style of object oriented programming. –  Kinjal Nov 21 '13 at 12:45

Bad idea. JavaScript is prototype-based, not object-oriented. Embrace it!

  • I would strongly advice you this book as well as his blog.

  • Mess around with a REPL (nodejs / chrome dev tools), try to understand the unexpected or surprising behaviours.

  • I found it useful sometimes to take a look at how your code is actually parsed, you can do this very easily online with the Esprima project.

  • Make sure you completely understand how the prototype chain, functions and type coercion work, they are, imo, the core concepts in javascript.

  • Get familiar with things such as IIFE (immediately invoked function expressions), scoping rules, etc.

share|improve this answer
5  
-1 for stating that OO requires classes. Many OO languages use classes, but it is not essential. en.wikipedia.org/wiki/Prototype-based_programming en.wikipedia.org/wiki/Object_oriented crockford.com/javascript/javascript.html –  itsbruce Sep 3 '13 at 15:35
    
The wikipedia page you link to isn't that correct imho. 'cloning existing objects to serve as prototypes' weut? ugh –  Pinoniq Sep 3 '13 at 15:47
    
Thanks for the advices! –  Jhonnatan Gonzalez Rodriguez Sep 3 '13 at 16:40
2  
@Pinoniq: That's how prototypes work. What's the problem? –  icktoofay Sep 4 '13 at 4:18
    
@icktoofay: It's not really accurate for JS. Prototypes in JS have very little to do with cloning; inheritance works mostly by setting the child's internal [[Prototype]] property to refer to the parent. It's a pretty big difference, in that adding or changing the parent's behavior also changes the child (which wouldn't happen, or would happen in very odd and broken'ish ways, if the parent were cloned). –  cHao Feb 17 '14 at 16:17

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.