受到乔尔斯回答的启发,这就是我的想法。我并没有费心使用纯 JS 解决方案——事实上,这是为了与Backbone.View
,但很容易适应其他情况。
当它到达视图的根元素时,它将停止攀爬节点树(this.el
)。从HammerJS事件标识的目标开始,它将寻找与指定选择器匹配的第一个元素,并返回undefined
如果没有找到这样的元素。
要在非 Backbone 环境中使用,只需传入对限制/包含元素的引用作为第三个参数(如 Jools 的解决方案中所示)并使用它来替换this.el
.
/**
* @param {Node}target - the target of the received event
* @param {String}selector - any jQuery-compatible selector
*/
getEventDelegate: function (target, selector) {
var delegate;
while (target && target != this.el) {
delegate = $(target).filter(selector)[0];
if (delegate) {
return delegate;
}
target = target.parentNode;
}
return undefined;
}
如果你有一个onTap
回调函数,它可能看起来像这样:
/**
* @param {Event}ev
*/
onTap: function (ev) {
var target = this.getEventDelegate(ev.target, "#desiredTarget");
if (target) {
// TODO something with the target...
}
}
为了把这一切连接起来,你需要这样的东西......
this._hammer = new Hammer(this.el);
this._hammer.on('tap', _.bind(this.onTap, this));
(并且不要忘记打电话this._hammer.destroy()
当你的视野被摧毁时!)