我刚开始尝试使用微型库而不是使用jQuery,我想将qwery与bean一起使用。如果我设置bean.setSelectorEngine(qwery);
为什么以下不起作用?
bean.on('.masthead', 'click', function () {
console.log('click fired');
});
我也在使用bonzo用于DOM实用程序,所以我将它设置为使用美元和qwery,这样我就可以像jQuery一样选择元素:例如$('.masthead')
。
function $(selector) {
return bonzo(qwery(selector));
}
这也行不通。我是否应该无法将以下内容与bean一起使用?
bean.on($('.masthead'), 'click', function () {
console.log('click fired');
});
也许我错过了bean文档中的重要内容..我需要做些什么才能解决这个问题?
此外,我尽量避免使用Ender,我试图将外部库保持在最低限度。
答案 0 :(得分:7)
是的,您可以在没有Ender的情况下将所有这些库一起使用。但是您必须自己连接这些库之间的所有连接。
这应该让你开始:
// 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');
});
希望有所帮助! :)
答案 1 :(得分:1)
为了说明问题,我采用了@Johnny的例子,因为我遇到了同样的问题,所以让它变得更通用了。这个例子在CoffeeScript + Underscore-Contrib中,但一般的想法是你不需要手工包装每个Bean函数,你可以通过操作参数在循环中完成它:
# 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
希望将来帮助某人。