fat / bean

an events api for javascript

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Pass event object as first argument when listening to objects?

opened this issue · comments

Hi

First of all, great work on Bean! I find myself using it all the time.

I am writing a bridge so I can switch between using the jQuery events API and Bean.
Everything goes fine except for events fired on objects. There is a difference in arguments passed to the callback function in jQuery and Bean and I am not sure which one has it right:

Setup:

var dummy = {};

Bean:

bean.add(dummy, 'message', function(message) {

    console.log(message); // (string) hello
});

bean.fire(dummy, 'message', ['hello']);

jQuery:

jQuery(dummy).on('message', function(message) {

    console.log(message); // (object) event
});

jQuery(dummy).trigger('message', ['hello']);

I'm not sure it's a case of having it right or wrong. I think what you're bumping up against is perhaps a more philosophical difference. jQuery treats events on non-DOM objects as if they were DOM events so you get the whole Event system complete with preventDefault() and stopPropagation() and all the rest of the standard properties you might find on an Event object received by a handler. Whereas Bean follows a more traditional pubsub model where you're simply passing messages around without the infrastructure to support bubbling etc.

Perhaps if you wanted something more jQuery-like you could just curry your handlers so they get what they need, maybe something along these lines:

function beanObjectAdd(obj, type, fn) {
  var event = {
          target: obj
        , type: type
        // whatever other properties you might need in your pseudo-Event
      }
    , newfn = function () { return fn.apply(null, [event].concat(Array.prototype.slice.call(arguments, 0))) }
  bean.add(obj, type, newfn)
  return newfn
}

of course then removing handlers by reference is tricky because you're adding the wrapped one so you could capture the returned newfn and reference that in your remove() call, or do something like Bean used to do and attach it to fn with something like: fn.__newfn = newfn so you always have it available and could do a corresponding beanObjectRemove() that uses it as the reference.

I hope that's interesting and/or helpful.

ooops, I didn't mean to close the issue, it can be reopened if you have anything more to add or a suggestion for a change that needs further discussion.

Thanks!

That explains a lot. I will try to curry then.