0

I have a plugin with the following structure:

(function($){

  function pluginName(el, options) {

    var _this = this;

    _this.defaults = {
      someOptions: '',
      onSlideStart: function() {},
      onSlideEnd: function() {},
    };

    _this.opts = $.extend({}, _this.defaults, options);

    $(el).on("slideStart", function() {
      _this.opts.onSlideStart.call();
    });

    $(el).on("slideEnd", function() {
      _this.opts.onSlideEnd.call();
    });
  }

  pluginName.prototype = {

    someFunctions: function() {
    }

  };

  $.fn.pluginName = function(options) {
    if(this.length) {
      this.each(function() {
        var rev = new pluginName(this, options);
        rev.init();
        $(this).data('pluginName', rev);
      });
    }
  };
})(jQuery);

If I call it the following way, everything is okay:

$('.element').pluginName({
  someOptions: 'full',
  onSlideStart: function() {
    console.log('slideStart!');
  },
  onSlideEnd: function() {
    console.log('slideEnd!');
  },
});

But I want to dynamic load the custom event handler like this:

(function($){

  function pluginName(el, options) {

    var _this = this;

    _this.defaults = {
      someOptions: '',
      onSlideStart: function() {},
      onSlideEnd: function() {},
    };

    _this.opts = $.extend({}, _this.defaults, options);

    for (var optionName in _this.opts) {
      var
        optionValue = _this.opts[optionName],
        optionType  = typeof(optionValue)
      ;

      if(optionType == 'function') {
        optionNames = optionName.split('on');
        eventName   = global.lowerFirstLetter(optionNames[1]);

        $(el).on(eventName, function() {
          eval('_this.opts.' + optionName + '.call();');
        });
      }
    }
  }

  ...

})(jQuery);

But this does not work. When I call the plugin with the "dynamic" part, it always call the slideEnd-function. So am I doing it wrong or is it just impossible with my plugin-pattern to call the custom event-handler dynamically?

1 Answer 1

1

Why use eval ? It's usually bad to use eval.

if(optionType == 'function') {
    optionNames = optionName.split('on');
    eventName   = global.lowerFirstLetter(optionNames[1]);

    $(el).on(eventName, _this.opts[optionName]);
  }

Try it and let me know.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.