2

I'm trying to figure out how I can wrap the click event. Eg this is the code I want.

$("#test").aclick(function() {
    alert('hi');
});

The only thing that aclick does is use the e.preventDefault automatically. Is it something like?

$.fn.aclick = function(e) {
   e.preventDefault();
   return $.fn.click.apply(this, arguments);
});

Thanks.

Schotime
  • 15,707
  • 10
  • 46
  • 75

1 Answers1

1

When binding a handler, the event object e doesn't exist yet. You need to create a default event handler that calls the supplied one:

$.fn.aclick = function (handler) {
    return this.each(function () {
        var el = this;
        $(el).click(function (e) {
            e.preventDefault();
            handler.call(el, e);
        });
    });
};
David Tang
  • 92,262
  • 30
  • 167
  • 149
  • I think i just went over into the deep end... to understand this code is going to take me a month. Care to offer an explanation, my javascript / jQuery is rusty... – erroric Jul 04 '14 at 18:09
  • Here's a start: http://stackoverflow.com/questions/4083351/what-does-jquery-fn-mean – erroric Jul 04 '14 at 18:14