jeudi 2 juin 2016

How would I set up JQuery into an Object Literal module?

I'm working on understanding the Object Literal design pattern in JS with JQuery. I have the code separated into different modules to lower the number of time the DOM has to be searched and be extendable. The problem is i don't know how to get the code to actually work. I understand why it's separated such as caching the Dom, binding events, and rendering the action of the slideToggle but the trouble is I don't fully understand how to apply the function to the event correctly.

The code I'm transferring from JQuery is as follows:

$(document).ready(function() {
  $('#menu-button').click(
    function(){
        $('#menu').slideToggle(400);
    }
  );
  $('.dropdown').click(
    function(){
        $('.dropdown-content').slideToggle(500);
    }
  );
});

The Object Literal Module I'm transferring this to is as follows:

(function() {
  var menu = {
    init: function() {
        this.cacheDom();
        this.bindEvents();
        this.action();
    },
    cacheDom: function() {
        this.$el = $('nav');
        this.$menu = this.$el.find('#menu');
        this.$menuButton = this.$el.find('#menu-button');
        this.$dropdown = this.$el.find('.dropdown');
        this.$dropdownContent = this.$el.find('.dropdown-content');
    },
    bindEvents: function() {
        this.$menuButton.on('click', this.slideToggle.bind(this));
        this.$dropdownContent.on('click', this.slideToggle.bind(this));
    },
    action: function() {
        this.slideToggle();
    },
  }
  menu.init();
})()

Any help would be greatly appreciated. Thank you.

Aucun commentaire:

Enregistrer un commentaire