off回调与原始on函数回调不同

时间:2019-05-01 02:36:11

标签: javascript html css html5 css3

首先,我没有使用jquery,而是在构建自己的普通javascript库。下面是我的off函数,然后是我的事件包装函数,看看我是如何制作off函数的,然后看看我的events函数。我所做的是创建自己的“关闭”回调函数,该函数与“打开”函数回调不同-因此,在删除事件侦听器时,我可以使用退出回调。我所做的一切有意义吗-可以讨论

off: function(event, selector, callback, capture) {

  if (typeof (selector) === 'function') {
    capture = callback;
    callback = selector || null;
  }

  selector = typeof selector == 'string' ? selector : null;
  capture = capture ? true : false;

  if(selector) {
    let obj = $(selector, this.$el);

    if(obj.$elems.length) {

      obj.$elems.forEach(function(el, i) {
        evts.remove(event, el, callback, capture);
      });

    } else if(obj.$el){        
      evts.remove(event, obj.$el, callback, capture);
    }

    return this;
  }


  if(this.$elems && this.$elems.length) {
    this.$elems.forEach(function(el, i) {
      evts.remove(event, el, callback, capture);
    });
  } else {
    evts.remove(event, this.$el, callback, capture);
  }

  return this;
}

事件包装器

var evts = (function () {
  'use strict';

  var listeners = [],
      add,
      remove;

  add = function (evt, elem, fn, capture) {
    var callback = function (evt) {      
      fn.call(elem, evt, evt && evt.target ? evt.target : window.event.srcElement);
    };

    listeners.push({
      evt: evt,
      elem: elem,
      fn: fn,
      callback: callback,
      capture, capture,
      removed: false
    });

    elem.addEventListener(evt, callback, capture);
  };

  remove = function (evt, elem, fn, capture) {

    var callback = function (evt) {
      return fn ? fn.call(elem, evt, evt && evt.target ? evt.target : window.event.srcElement) : null;
    };

    listeners.forEach(function (obj, i) {
      if (obj.evt === evt && obj.elem === elem && 
          !obj.removed) {
        obj.removed = true;

        if(callback && callback !== obj.callback) {
          callback();
        }

        callback = obj.callback;
        listeners.splice(i, 1);

        return false;
      }
    });

    elem.removeEventListener(evt, callback, capture);
  };

  return {
    add: add,
    remove: remove
  };
}());

示例:

$('#btn').on('click', function(e) {
    $(this).off('click', function(e) { alert('good bye') });
});

0 个答案:

没有答案