JavaScript assign function within variable to click event within plugin

时间:2017-06-15 09:54:40

标签: javascript

I have got a plugin where I assign click event functions based on a string. However I don't think I can use Window['variable name'] as the variable is within my plugin scope not the window scope.

How would I go about assigning the EventLeft/EventRight/EventClose variable anonymous functions to the click event of the querySelectorAll loop?

(function() {

  // Constructor
  this.MarvLightbox = function() {

    // Initialise plugin
    this.open();
  };

  MarvLightbox.prototype.open = function() {

    setupLightbox.call(this);
  };

  function setupLightbox() {

    var createExpand = function(img) {

          // Generate lightbox HTML and append
          var instance = this,
              html = buildHTML(instance.options.html),
              EventClose = function() {
                // Do stuff
              },
              EventLeft = function() {
                // Do stuff
              },
              EventRight = function() {
                // Do stuff
              };

          // Lightbox is active
          instance.active = true;

          // Assign click events
          html.getElementsByClassName('image')[0].src = img;

          html.querySelectorAll('[data-click]').forEach(function(e) {
            e.addEventListener('click', function() { instance[this.dataset.click]; });
          });

    }.bind(this);

  }

});

2 个答案:

答案 0 :(得分:1)

虽然你自己的答案会起作用但它不是真的可读,因此不容易维护。

将您的功能存储在对象中,并使用key进行访问。

var events = {
  EventClose: function() {
    instance.active = false;
    item.current = null;
  },
  EventLeft: function() {
    if (item.current !== 0) {
      item.current = item.current - 1;
    } else {
      item.current = instance.images_count;
    }
  },
  EventRight: function() {
    if (item.current !== instance.images_count) {
      item.current = item.current + 1;
    } else {
      item.current = 0;
    }
  }
}

html.querySelectorAll('[data-click]').forEach(function(e) {
  e.addEventListener('click', events[e.dataset.click]);
})

答案 1 :(得分:0)

不太清楚为什么这个问题如此令人困惑。管理找到解决方案:

events = function(fnstring) {
  switch(fnstring) {
      case 'EventClose': (function() {
        instance.active = false;
        item.current = null;
      }()); break;
      case 'EventLeft': (function() {
        if (item.current !== 0) {
          item.current = item.current - 1;
        } else {
          item.current = instance.images_count;
        }
      }()); break;
      case 'EventRight': (function() {
        if (item.current !== instance.images_count) {
          item.current = item.current + 1;
        } else {
          item.current = 0;
        }
      }()); break;
    }
};

html.querySelectorAll('[data-click]').forEach(function(e) {
  e.addEventListener('click', function() { events(e.dataset.click); });
});