根据变量添加 Polymer 手势监听器
Add Polymer gesture listeners depending on variable
如何添加手势侦听器而不直接将它们添加到模板或 'listeners' 属性 中,以便我可以根据选项添加它们。
例如
Polymer({
is: 'my-element',
properties: {
enableDrag: Boolean
},
listeners: {
// DO NOT DEFINE HERE
// 'viewer.track': 'handleTrack'
},
ready: function() {
if(this.enableDrag) {
// attach listeners to an element here, something like
// this.$.viewer.addEventListener('track', this.boundHandleTrack);
}
}
});
我已经尝试了 addEventListener('track', this.boundHandleTrack)
和 setAttribute('on-track', 'handleTrack')
,但都无法正常工作。
谢谢!
您应该可以使用 listen
方法强制添加手势。 Fwiw,最好观察 enableDrag
而不是依赖 ready
时间配置的 属性。
不幸的是,目前没有 unlisten
,因为 (iirc) 手势代码不支持 removing 1.0 的侦听器(即将推出) [Tm值])。 boundHandleTrack
的恶作剧在里面,因为没有 unlisten
。
如果它适用于您的用例,那么总是在目标节点上监听 on-track
并且不操作处理程序(就像我必须在下面做的那样)会更容易。
properties: {
enableDrag: {
type: Boolean,
observer: 'enableDragChanged'
},
boundHandleTrack: {
value: function() { return this.handleTrack.bind(this); }
}
},
enableDragChanged: function(drag) {
if (drag && this.boundHandleTrack) {
this.listen(this.$.viewer, 'track', 'boundHandleTrack');
this.boundHandleTrack = null;
}
},
handleTrack: function(e) {
if (!this.enableDrag) return;
// ... otherwise do stuff
}
如何添加手势侦听器而不直接将它们添加到模板或 'listeners' 属性 中,以便我可以根据选项添加它们。
例如
Polymer({
is: 'my-element',
properties: {
enableDrag: Boolean
},
listeners: {
// DO NOT DEFINE HERE
// 'viewer.track': 'handleTrack'
},
ready: function() {
if(this.enableDrag) {
// attach listeners to an element here, something like
// this.$.viewer.addEventListener('track', this.boundHandleTrack);
}
}
});
我已经尝试了 addEventListener('track', this.boundHandleTrack)
和 setAttribute('on-track', 'handleTrack')
,但都无法正常工作。
谢谢!
您应该可以使用 listen
方法强制添加手势。 Fwiw,最好观察 enableDrag
而不是依赖 ready
时间配置的 属性。
不幸的是,目前没有 unlisten
,因为 (iirc) 手势代码不支持 removing 1.0 的侦听器(即将推出) [Tm值])。 boundHandleTrack
的恶作剧在里面,因为没有 unlisten
。
如果它适用于您的用例,那么总是在目标节点上监听 on-track
并且不操作处理程序(就像我必须在下面做的那样)会更容易。
properties: {
enableDrag: {
type: Boolean,
observer: 'enableDragChanged'
},
boundHandleTrack: {
value: function() { return this.handleTrack.bind(this); }
}
},
enableDragChanged: function(drag) {
if (drag && this.boundHandleTrack) {
this.listen(this.$.viewer, 'track', 'boundHandleTrack');
this.boundHandleTrack = null;
}
},
handleTrack: function(e) {
if (!this.enableDrag) return;
// ... otherwise do stuff
}