samedi 27 février 2016

Javascript scope issue in higly customizable plugin pattern

I'm trying to build a Javascript plugin. It will be a slider/carousel with the ability to add options and actions for every single slide. I know that there are already similar plugins around, but first of all I want to make some practice in building a plugin and then I think it might be easier to extend it the way I want, should I need it.

It's my first attempt in building a Javascript plugin and after having read about different design patterns I thought that this would fit my needs: http://ift.tt/1512vDg

So, my html would be something like this:

<div class="container">
  <div class="item" data-step-in="stepin" data-step-out="stepout">item</div>
  <div class="item" data-step-in="stepin2" data-step-out="stepout2">item</div>
  <div class="item" data-step-in="stepin3" data-step-out="stepout3">item</div>
</div>

Ideally I want to call the plugin on the container element and have it set all the options for each element:

$('.container').slider();

The basic plugin structure is:

(function(window, $) {
  var Plugin = function(elem, options) {
    this.elem = elem;
    this.$elem = $(elem);
    this.options = options;
    this.items = {};
  };

  Plugin.prototype = {
    defaults: {
      message: 'Hello world!',
      itemsClass: '.item'
    },
    init: function() {
      this.config = $.extend({}, this.defaults, this.options);

      $(this.config.itemsClass).each(function(i, obj) {
        console.log(i, obj);
        this.items[i][item] = obj;    <--- problem!
      });

      return this;
    },
  };

  Plugin.defaults = Plugin.prototype.defaults;

  $.fn.slider = function(options) {
    return this.each(function() {
      new Plugin(this, options).init();
    });
  };

  window.Plugin = Plugin;
})(window, jQuery);

In the init function I thought to iterate over the items, and store them, with all the options, in a global object. This is where I fail. Inside the each cycle this refers to a single item of the iteration. So, from here, how shall I refer to this.items inside the constructor? What's the best approach here? Is the pattern wrong for this use?

Aucun commentaire:

Enregistrer un commentaire