jQuery

A well known JavaScript Framework that is used by three out of four websites all over the world. It helps you navigate and manipulate the DOM-Tree. I like to show you how I work with jQuery and how I write code for websites.

This is that – Classes first

There are not enough buzzwords these days so let me use “class first” to describe a very nice workflow. It is about simple classes which make change requests less complicated than hacking JS code in one big file and doing workarounds in workarounds. I’ve seen that out there, this is a mess no one likes to maintain. Classes to the rescue:

  • Reusable code: One class can inherit another to reuse code or just change small pieces of it. Don’t repeat yourself!
  • Simpler to use: Hide unnecessary code and only show public functions to the autocomplete of your IDE. Keep it stupid simple!
  • Design benefits: The more features or post-types you have the more you benefit from the OOP structure. Single purpose helps find things faster.
  • Easy maintenance: Legacy code needs updates and there will be new features. All above allow that in the blink of an eye.

So lets write a class that can be used as a jQuery extension. This is actually shorter than everything I needed to convince you to classes and I hope this does too:

( function( $ ) {
  $.fn.newsletter = function () {
    // here you can hack
    $(this).submit();
  }
)( jQuery );

Simple as that. A function is defined which can be used as a class in JavaScript. It is defined on top of the jQuery class/function. For now we have something that works like this:

$('#foo').newsletter();

This is good for simple and small things. For more complex things or a structured way from the start the function can become a class. Just fill it with other functions:

( function( $ ) {
  $.fn.newsletter = function () {
    // "this" will contain what you selected with jQuery
    // like the form in $('#form')
    var self = this;

    // A method.
    // Call this via "jQuery('#form').newsletter.send()"
    self.send = function () {
      // self now always contains
      var data = $(self).serialize();

      // .. some AJAX magic
    }
  }
)(jQuery);

The “self ” variable keeps the context or DOM node you’ve selected via “$(‘#foo’)” or other selector. It is needed because the “this” variable will change inside a function and the jQuery-Context is gone. So better keep it safe in the “self” variable.