【问题标题】:Titanium/ Alloy/ Appclerator: Remove event listener from a List ItemTitanium/Alloy/Appclerator:从列表项中删除事件侦听器
【发布时间】:2017-04-21 14:37:59
【问题描述】:

我有一个ListView 有点像这样:

<ListView>
    <Templates>
        <ItemTemplate name="example">
            <View id="wrapper" onClick="onClickExampleButton">
                <Label>Click Me</Label>
            </View>
        </ItemTemplate>
    </Templates>

    <ListSection id="ls">
        <ListItem template="example"></ListItem>
        <ListItem template="example"></ListItem>
        <ListItem template="example"></ListItem>
    </ListSection>
</ListView>

我想防止双击onClickExampleButton函数。

到目前为止,在控制器中我有这样的代码:

function onClickExampleButton(e) {
     var item = $.ls.getItemAt(e.itemIndex);
     // TODO: I want to disable the onClick eventListener here

     someLongAsyncFuncToServer(function() {
         // TODO: I want to re-enable the onClick eventListener here
     })
}

通常删除事件侦听器就像

一样简单
$.objId.removeEventListener(onClickExampleButton)

并重新添加它很简单:

$.objId.addEventListener(onClickExampleButton)

但是,我不确定如何在 ListItem 上实现这一目标

【问题讨论】:

    标签: titanium appcelerator appcelerator-titanium titanium-alloy appcelerator-alloy


    【解决方案1】:

    我相信您可以通过使用元素触发的事件的源 ID 来实现这一点。您唯一需要注意的是,因为事件会冒泡到父层次结构,所以任何子视图也可以调用单击事件,从而为您提供意外的源 ID。

    要解决您的查询,您可以安全地使用此代码:

    function onClickExampleButton(e) {
         var item = $.ls.getItemAt(e.itemIndex);
    
         // TODO: I want to disable the onClick eventListener here
         e.source.touchEnabled = false;
    
         someLongAsyncFuncToServer(function() {
             // TODO: I want to re-enable the onClick eventListener here
             e.source.touchEnabled = true;
         })
    }
    

    并像这样对您的 XML 代码进行一些更改:

    <ListView>
        <Templates>
            <ItemTemplate name="example">
                <View id="wrapper" onClick="onClickExampleButton">
                    <Label touchEnabled="false">Click Me</Label>
                </View>
            </ItemTemplate>
        </Templates>
    
        <ListSection id="ls">
            <ListItem template="example"></ListItem>
            <ListItem template="example"></ListItem>
            <ListItem template="example"></ListItem>
        </ListSection>
    </ListView>
    

    这里要注意的是,首先您在 View (with id = wrapper) 内的 Label 上设置 touchEnabled = 'false',它将确保点击事件不会被标签触发,并且只会被父级冒泡和触发。

    接下来,在点击事件方法中,您使用的是 e.source,它现在是您的包装视图。

    如果您没有在 Label 上设置 touchEnabled=false,那么 e.source 还可以包含 标签 引用。您可以阅读有关事件冒泡的更多信息,这将帮助您了解如何在 Titanium 中有效地使用事件处理。

    【讨论】:

      【解决方案2】:

      我会在对象上放置一个属性并使用它来确定状态。例如, 单击按钮时设置一个变量,然后在长时间运行 Async 函数后更改它...这样,如果状态为运行,则忽略单击。一旦它不再运行,然后接受点击。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-04
        • 2017-08-13
        • 2022-08-03
        • 1970-01-01
        • 2011-03-07
        • 1970-01-01
        相关资源
        最近更新 更多