HI I am looking into object literals, a topi that I am afraid I really don't know much about. Anyway, I thought I'd try something but I didn't get it to work and I am not sure what I am doing wrong.
I have an HTML page:

<html>
    <head>
        <title>This is a test</title>
        <link rel="stylesheet" type="text/css" href="style.css">
        <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
        <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
        <div class="container">
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse bibendum turpis neque, et pretium arcu euismod eu. Etiam vulputate vitae nunc sit amet laoreet. Sed euismod justo sit amet interdum tincidunt. Donec pulvinar nec justo quis aliquet. Suspendisse at orci sed ante varius vehicula non vel enim. Donec posuere sollicitudin tristique. Aliquam imperdiet erat ultrices odio lobortis viverra. Integer id erat vitae quam elementum elementum non vitae leo. Nam velit enim, cursus id urna vitae, adipiscing congue odio. Nullam eleifend tristique rhoncus. In vel neque a sem mollis convallis. Mauris molestie est sit amet dui imperdiet, a pharetra nibh scelerisque. Nam massa purus, vulputate a purus sed, bibendum porttitor neque.</p>
            <p>Proin adipiscing, ipsum eget malesuada sodales, mi purus sollicitudin ligula, sed ultrices massa ipsum id sem. Nulla eu laoreet dui. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Cras sit amet imperdiet turpis, sit amet rutrum justo. Nunc ultricies, enim eget consectetur laoreet, lorem ipsum posuere nulla, in lacinia lorem risus et ipsum. Nulla eros turpis, faucibus sit amet pharetra eu, pretium eu libero. Nam accumsan ullamcorper odio sit amet ultrices. Vivamus pretium scelerisque quam sed ultrices. Suspendisse euismod in neque quis volutpat.</p>
            <p>Interdum et malesuada fames ac ante ipsum primis in faucibus. Proin urna nisi, pharetra et sodales mollis, mollis sit amet metus. Sed leo dui, condimentum vel fermentum laoreet, interdum vel massa. Praesent sagittis tincidunt auctor. Morbi sit amet diam sit amet metus facilisis tincidunt. Suspendisse non libero ipsum. Sed vitae cursus dui. Nullam pharetra auctor lorem, nec facilisis est lobortis vel. Vestibulum tincidunt turpis ut libero congue pharetra. Aliquam erat volutpat. Nam imperdiet lectus eu dui pulvinar, eget consequat nibh fermentum.</p>
            <p>Cras nibh quam, feugiat non libero eget, ultricies eleifend arcu. Donec a eleifend massa. In in pretium sem. Donec ultricies malesuada nisi, quis fringilla est egestas sed. Mauris placerat ac metus eu suscipit. Sed imperdiet eros non justo interdum, vitae dignissim augue dictum. Nullam vulputate quis elit non dictum. Phasellus pretium orci at erat auctor, nec vestibulum ligula consequat. Etiam lacinia, urna ac congue imperdiet, erat eros pulvinar metus, id dapibus magna velit sodales quam. Donec quis dignissim velit. Etiam quis quam et quam convallis ultrices at eu urna. Pellentesque pulvinar erat nibh. Nunc iaculis id lacus a consectetur. In hac habitasse platea dictumst. Nulla vel odio ut nulla vulputate imperdiet vel vel dui. Ut ut ipsum vehicula, vehicula nunc nec, fermentum nunc.</p>
            <button>Contact form</button>
            <form class="contactForm">
                <div class="row">
                    <label>Enter your name</label>
                    <input type="text">
                </div>
                <div class="row">    
                    <label>Enter your surname</label>
                    <input type="text">
                </div>
                <div class="row">
                    <label>Enter your age</label>
                    <input type="text">
                </div>
            </form>

        </div>
    </body>
</html>

And the css that hides the form:

.container{
    width:900px;
    margin:0 auto;
    background-color:pink;
    padding:10px;
}
.contactForm{
    margin-top:20px;
    display:none;
}
.contactForm label{
    display:inline-block;
    width:200px;
    margin-top:10px;

}
.contactForm label input{
    margin-left:10px;
}

And then I thought, let's get the form to appear when the button is clicked. Now, everybody knows how to do it really easily without an object literal, but I tought I'd use one and try.
Here is the script:

$(document).ready(function(){
    //alert("ohi");
});

var form = { //object literal
    init: function(){
        //alert("hello!");      
        console.log($(this));
        $("button").click(function(){
                console.log("inside the click " + $(this));

        });     
    }   
};

form.init();

A couple of things to observe: this script sits in an external file and it is referenced in the HTML inside the head tag as you can see.
So in here I have created an object literal, assigned it an init function that gets called with form.init() and so far so good, but then when I add

$("button").click(function(){
                    console.log("inside the click " + $(this));

            }); 

things don't work. When I click the button nothing happens, not even an error in the console. Is that because the click function is not inside a document ready?

Recommended Answers

All 11 Replies

Member Avatar for iamthwee

I don't bother with checking forms init status.

I would just put the button click event INSIDE document ready()

hi thanks, yes I know that will work (that's the way I would do it anyway) but I thought I'd experiment with the object literals :-). So you think that it doesn't work because it doesn't sit inside a document ready and therefore it tries to add the click handler before the DOM is ready? In which case le tme ask you, do you think that if I had the script in the HTML file at the end of the body tag, it would work?

Member Avatar for iamthwee

Don't quote me on this as I am unsure. But I never use form init. It just seems to complicate matters. I just load the custom jquery underneath the body tag. I think this is normal practice nowadays to load js under the body.

I put all my functions in document ready.

yep that's what I generally do too :-), but this object literal thingy bugged me, that's why I thought I'd give it a go...and I wasn't that successful I must say!

ah, good news, with a few changes here and there now I got it to work. I had to take out the click handler and wrap it inside a document.ready() though

var form = { //object literal
    init: function(){       
        console.log($(this) + "function called");       
    }   
};
$(document).ready(function(){
    $(".theButton").click(function(){
        form.init();
    });
});

what is its practical use ?

commented: yup I thought that too +14

Violet, you have discovered the problem but you don't need to refactor your original code to quite that extent :

Try :

$(document).ready(function(){
    form.init();
});

var form = { //object literal
    init: function(){
        $("button").click(function(){
            console.log("inside the click " + $(this));
        });     
    }   
};

or, avoiding the global namespace :

$(document).ready(function(){
    var form = { //object literal
        init: function(){
            $("button").click(function(){
                console.log("inside the click " + $(this));
            });     
        }   
    };
    form.init();
});

And for those who think this might be just an academic exercise, partitioning code into a number of namespaces is actually very useful when things get complex. I do it all the time.
Object literals are fine. The Module Pattern is a very formal approach to achieve the same end (and is actually a glorified object literal when all is said and done).

Member Avatar for iamthwee

I still don't understand the point. Airshow is it like defining scope?

I can understand the importance server side but with js I hardly see the point. Seeing as you can just reference a dom's id as all id's are supposed to be unique. Can you elaborate on why this is useful.

Cheers

Iamthwee, namespacing your code is something we should all consider in order to keep our javascript tidy. It's not specifically to do with runtime environemental issues. In other words it's something we might do even in the absence of a DOM - say we were writing some node.js for example.

And yes, "defining a scope" is a good way to think of it. Strictly speaking javascript only has global scope and functional scope; but we also have javascript plain objects and constructed objects (created with the new operator). Together these provide ways in which we can define private and public members, and avoid name collisions; all very desirable in complex code, to insulate the "module" we are currently working on from interference by other code (eg libs, or code written previously by yourself or another programmer).

Imagine what chaos might ensue if all members were in the global namespace. Think how careful you would have to be when using a 3rd party lib not to overwrite some critical aspect of that lib!

commented: Thank you +14
Member Avatar for iamthwee

Thank you for that explanation airshow. I think you are using js with a level of mastery I'm not quite accustomed to so the perceived benefits are not apparent to me... YET.

That being said... I have used wordpress plugins a few times and I know they define a different global namespace to avoid conflicts

$document.read() so I can most definitely see the benefits there.

Imagine what chaos might ensue if all members were in the global namespace. Think how careful you would have to be when using a 3rd party lib not to overwrite some critical aspect of that lib!

This is why you should write your own code and if necesary your own (specific to the project algo ) libs.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.