Skip to content

Instantly share code, notes, and snippets.

@stevenyap
Created April 21, 2014 13:43
Show Gist options
  • Select an option

  • Save stevenyap/11143094 to your computer and use it in GitHub Desktop.

Select an option

Save stevenyap/11143094 to your computer and use it in GitHub Desktop.
OOP in jQuery
(function($) {
  // create a class in jQuery scope
  $.landingVideo = function(options) {
    // define a self to be used as the main var
    // using 'this' breaks in event passing
    var self = {

      options: $.extend({
        video_player_id: '',
        video_player_container: ''
      }, options),

      start: function() {
        video_player = document.getElementById(self.options.video_player_id);
        video_player.play();
        $('#' + self.options.video_player_id).bind("ended", self.end);
      },

      // using self here saves the day!
      // using 'this' will not work
      end: function(event) {
        self.options.video_player_container.fadeOut();
        start_tiles_animation();
      },
    };

    // return a separate object literal instead of self
    // this pattern exposes only the functions you want (encapsulation)
    return { 
      start: self.start
    };
  };
})(jQuery);

// this is how you use your object
landing_video = new $.landingVideo({
  video_player_id: 'landing-video-player',
  video_player_container: $('.landing-video')
});
landing_video.start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment