0

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?

Edited by Violet_82

4
Contributors
11
Replies
54
Views
3 Years
Discussion Span
Last Post by Troy III
0

I don't bother with checking forms init status.

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

0

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?

0

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.

0

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!

0

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();
    });
});
0

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).

0

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

1

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!

Edited by Airshow

Votes + Comments
Thank you
0

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.

0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.