5

I have just started trying out micro libraries instead of using jQuery and I'd like to use qwery with bean. If I set bean.setSelectorEngine(qwery); why does the following not work?

bean.on('.masthead', 'click', function () {
    console.log('click fired');
});

I am also using bonzo for DOM utility, so I have set it to use the dollar along with qwery so I can select elements in a jQuery-like fashion: e.g. $('.masthead').

function $(selector) {
    return bonzo(qwery(selector));
}

This also does not work. Should I not be able to use the following with bean?

bean.on($('.masthead'), 'click', function () {
    console.log('click fired');
});

Perhaps I have missed something important in the bean documentation.. What do I need to do to fix this?

Also, I am trying to avoid using Ender if at all possible, I am trying to keep my external libraries down to a minimum.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Zander
  • 2,471
  • 3
  • 31
  • 53

2 Answers2

7

Yes, you can use all those libraries together without Ender. But you are going to have to wire up all the connections between those libraries yourself.

This should get you started:

// make Bean and Bonzo use Qwery 
// as their internal selector engine 
bean.setSelectorEngine(qwery);
bonzo.setQueryEngine(qwery);

// to use $ instead of bonzo
function $(selector, root) {
    return bonzo(qwery(selector, root));
};

// $() will return a bonzo object
// so if you want to be able to use 
// bean's methods on the bonzo object 
// like $().on()
// you are going to have to extend bonzo
bonzo.aug({
  on: function (eventName, callback) {
    return this.each(function (elem) {
        return bean.on(elem, eventName, callback);
    });
  },

  // do the same for bean's other methods (fire, off, etc)
});

// now you should be able to do this:
$('.masthead').on('click', function () {
    console.log('click fired');
});

Hope that helps! :)

John
  • 3,866
  • 6
  • 33
  • 37
1

Just to chime in, I took @Johnny's example above and made it a little more generic as I had the same problem. This example is in CoffeeScript + Underscore-Contrib, but the general idea is that you don't need to wrap every Bean function by hand, you can do it in a loop by manipulating the arguments:

  # Setup Qwery/Bonzo
  window.$ = (selector, root) ->
    bonzo qwery(selector, root)

  # Glue Bean event handling into Bonzo/Qwery
  events =
    clone : ->
      args = _.toArray arguments
      bean.clone.apply null, args

  _.each ['on','one','off','fire'], (ev) ->
    events[ev] = ->
      args = _.toArray arguments
      this.each (elem) ->
        bean[ev].apply null, _.cons(elem, args)

  bonzo.aug events

Hope it helps someone in the future.

Darren Newton
  • 2,847
  • 1
  • 29
  • 31