gpt4 book ai didi

angular - Ionic 2 - 为 "long press"事件指令设置回调

转载 作者:太空狗 更新时间:2023-10-29 18:07:02 25 4
gpt4 key购买 nike

我正在尝试在元素上添加自定义 longPress 事件指令,因为 (press)="callback_function()"将导致 ion-list 无法再滚动。不管是否有错误,我发现我需要添加一个自定义手势指令来添加对新属性的支持,在这种情况下我称之为 longPress。它工作得很好,除了我不知道如何添加回调函数:-)

我已经学习了教程 ( http://roblouie.com/article/198/using-gestures-in-the-ionic-2-beta/ )

“press-directive”是在 src/components/press-directive/press-directive.js 中创建的,如下所示:

import { Directive, ElementRef, OnInit, OnDestroy } from '@angular/core';
import { Gesture } from "ionic-angular/gestures/gesture";

/**
* Generated class for the PressDirective directive.
*
* See https://angular.io/docs/ts/latest/api/core/index/DirectiveMetadata-class.html
* for more info on Angular Directives.
*/

@Directive({
selector: '[longPress]' // Attribute selector
})


export class PressDirective implements OnInit, OnDestroy {
el: HTMLElement;
pressGesture: Gesture;

constructor(el: ElementRef) {
this.el = el.nativeElement;
}

public theCallback() {

}

ngOnInit() {
this.pressGesture = new Gesture(this.el);
this.pressGesture.listen();

// instead of this..
this.pressGesture.on('press', (event) => {
console.log('pressed!!');
});

// i want the callback to come from the template like this:
// <ion-col (longPress)="showActionSheet(object)">
}

ngOnDestroy() {
this.pressGesture.destroy();
}
}

home.module.ts 中,我在导入中添加了指令:

import { PressDirective } from "../../components/press-directive/press-directive";

我在声明中添加了它:

declarations: [
Home,
PressDirective
],

home.html中,我是这样实现的:

<ion-col (longPress)="showActionSheet(relevantObject)">...

我已经删除了大部分不重要的内容:-)

当我长按时,它会返回以下内容:

console.log('pressed!!');

但我无法思考如何从模板元素中支持实际的回调函数。

任何帮助或提示将不胜感激..

最佳答案

对于仍然有此问题的任何人,我遇到了非常相似的事情,并且Steen's answer对于确定添加回调非常有帮助。

但是,我想补充一点说明,因为我认为应该区分“按下”和“释放”(或“加压”)。

根据 HammerJS docs(ionic 用于 Gestures ),有一个 "press" 事件,还有一个 "pressup" 事件,它在按下时触发。

您实际上可以为每个事件(presspressup)包含一个 @Output:

/*
* The first output will emit when the timeout is reached for press,
* and the second will emit when the press gesture is released.
*/

@Output('long-press') onPress: EventEmitter<any> = new EventEmitter();
@Output('long-press-up') onPressUp: EventEmitter<any> = new EventEmitter();

然后,在 @ngOnInit 中,用每个相应的发射器响应每个事件:**

this.pressGesture.on('press', (event) => {
this.onPress.emit(event);
});

this.pressGesture.on('pressup', (event) => {
this.onPressUp.emit(event);
});

这样,您就可以为每个手势事件(在模板/组件中)支持一个单独的回调函数:

<ion-col (long-press)="longPressed(object)" (long-press-up)="longPressReleased(object)">
...
</ion-col>

希望这能增加一些信息/清晰度。

关于angular - Ionic 2 - 为 "long press"事件指令设置回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43492833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com