7
\$\begingroup\$

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();   
});
\$\endgroup\$
1
  • 6
    \$\begingroup\$ Contrary to some of the answers below, note that a lot of people define prototypes as a form of OOP stackoverflow.com/questions/186244/… \$\endgroup\$ Commented Sep 3, 2013 at 15:31

3 Answers 3

1
\$\begingroup\$

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.

\$\endgroup\$
12
  • 2
    \$\begingroup\$ That “revealing pattern” is not related to OOP. \$\endgroup\$ Commented Sep 3, 2013 at 0:44
  • \$\begingroup\$ why not, don't is encapsulation the key concept of OOP? \$\endgroup\$ Commented Sep 3, 2013 at 2:06
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ Commented Sep 3, 2013 at 5:30
  • 1
    \$\begingroup\$ @icktoofay here you can see an example of inheritance. \$\endgroup\$ Commented Sep 4, 2013 at 12:17
  • 1
    \$\begingroup\$ 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 \$\endgroup\$ Commented Sep 4, 2013 at 15:39
0
\$\begingroup\$

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.

\$\endgroup\$
4
  • 5
    \$\begingroup\$ -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 \$\endgroup\$ Commented Sep 3, 2013 at 15:35
  • \$\begingroup\$ The wikipedia page you link to isn't that correct imho. 'cloning existing objects to serve as prototypes' weut? ugh \$\endgroup\$ Commented Sep 3, 2013 at 15:47
  • 2
    \$\begingroup\$ @Pinoniq: That's how prototypes work. What's the problem? \$\endgroup\$ Commented Sep 4, 2013 at 4:18
  • \$\begingroup\$ @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). \$\endgroup\$ Commented Feb 17, 2014 at 16:17
-7
\$\begingroup\$

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.

\$\endgroup\$
9
  • \$\begingroup\$ 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!!! \$\endgroup\$ Commented Sep 3, 2013 at 13:58
  • 6
    \$\begingroup\$ -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. \$\endgroup\$ Commented Sep 3, 2013 at 15:40
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Commented Sep 3, 2013 at 15:45
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ Commented Sep 3, 2013 at 16:12
  • 3
    \$\begingroup\$ @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. \$\endgroup\$ Commented Nov 21, 2013 at 12:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.