Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Four questions about nettuts "30 days to learn jquery"

I'm doing a free jQuery course on nettuts called 30 days to learn jquery by Jeffrey Way and I have four things I'm really stumped about, first off here's the code:

(function() {
    $('html').addClass('js');

    var contactForm = {
            container: $('#contact'),

        init: function() {
            $('<button></button>', {
                text: 'Contact Me'
            })
                .insertAfter('article:first-child   ')
                .on('click', this.show);
            },
        show: function() {
            contactForm.container.slideDown(500);
        }                       
    };

    contactForm.init(); 

})();

It basically slides down a contact form when you click the "contact Me" button on the website. My questions are:

  1. Whats the whole point of "init" and do you need it?
  2. why is the whole jquery code inside of a variable?
  3. on the string of code that says .on('click', this.show); why do you need this in this.show?
  4. finally, why do you need contactForm.container.slideDown(500); as in why can't you just say container.slideDown(500); or $('form.contact').slideDown(500); (by the way the id of the form that slides down is contact.
like image 225
Michaelslec Avatar asked Jul 16 '12 23:07

Michaelslec


1 Answers

Whats the whole point of "init" and do you need it?

This code is creating a javascript object, with a function called init, then calling that function. You could just as easily move this code outside of the object, but then you wouldn't be able to reuse it, and do other object oriented things with it.

why is the whole jquery code inside of a variable?

In Javascript (not just jQuery) everything is an object. Functions are an object, object are objects, etc. This code is creating an object with 3 variables: container, which stores a jquery object; init, which stores a function; and show which stores a function. This is then being assigned to the contactform variable.

on the string of code that says .on('click', this.show); why do you need this in this.show?

this.show references the .show() method on the this object. In this context this is the contactForm object, and show is the show function being passed as an object (but not called). The effect of this is when the button is clicked, the show function is called.

finally, why do you need contactForm.container.slideDown(500); as in why can't you just say container.slideDown(500); or $('form.contact').slideDown(500); (by the way the id of the form that slides down is contact.

Because container is a property (i.e. a variable) that belongs to the contactform object. You could do something like $('#contact').slideDown(500); but you already have a reference to $('#contact') in contactform.container, and not using it will cause unnecessary overhead.

like image 83
Kyle Trauberman Avatar answered Nov 14 '22 20:11

Kyle Trauberman