Domanda

This is the code that works properly:

bonzo.aug({
  bind: function (event, handler) {

    if (this[0].attachEvent)
            this[0].attachEvent('on'+event, handler);
          else
            this[0].addEventListener(event, handler);
        },
  unbind: function (event, handler) {
            if (this[0].detachEvent)
              this[0].detachEvent('on'+event, handler);
            else
              this[0].removeEventListener(event, handler);
          },
  once: function (event, handler) {
          function doOnce(e) {
            bonzo(this).unbind(event, doOnce);
            handler.call(this, e);
          }
          this.bind(event, doOnce);
        }
});

But then when I try to consolidate and soup parts of it up a little, unbind and once break:

(function($){
  $.ieEventApi = !!window.attachEvent; // !-[1,];

  $.addEventListener = $.ieEventApi ? "attachEvent" : "addEventListener",
  $.removeEventListener = $.ieEventApi ? "detachEvent" : "removeEventListener",
  $.onForIe = $.ieEventApi ? 'on' : '',
  $.adaptEventHandlerForIe = function(f){
    return function(e){
      e.target = e[(e.target ? e.target : (e.srcElement || document))];
      return f(e);
    };
  };



  $.aug({
    bind: function (event, handler) {
            for(var i = 0; i < this.length; i++) // I'd use Bonzo.each if I could find any documentation for its use.. :-\
                this[i][$.addEventListener]($.onForIe+event, $.adaptEventHandlerForIe(handler), false); // The "false" is superfluous on IE, but apparently not problematically so.
            return this;
          },
    unbind: function (event, handler) {
              for(var i = 0; i < this.length; i++)
                this[i][$.removeEventListener]($.onForIe+event, $.adaptEventHandlerForIe(handler), false); 
              return this;
            },
    once: function (event, oncehandler) {
            // This just calls the other two, which already handle iteration.
            this.bind(event, doOnce);
            return this;

            function doOnce(e) {
              $(e.target /*Or should I be using e.target here?*/ ).unbind(event, doOnce);
              oncehandler.call(this, e);
            }
          }
  });
})(bonzo);
È stato utile?

Soluzione

Shouldn't the following line

e.target = e[(e.target ? e.target : (e.srcElement || document))];

be something like

e.target = e[e.target ? 'target' : (e.srcElement ? 'srcElement' : 'document')];

? I mean, when you're referring to a prop in an object and using square brackets you should write the inner value in string format. So e.etc should become e['etc'].

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top