Ext JS 的点击事件

7

我有以下事件:

Ext.onReady(function() {

    Ext.select('.gallery-item img').on('click', function(e) {
        Ext.select('.gallery-item').removeClass('gallery-item-selected');
        Ext.get(e.target).parent().addClass('gallery-item-selected');
    });

});

当页面加载时,这很好用。

但是,我动态创建了一个带有图像的类为gallery-item的附加div。一旦我创建了新项目,点击事件就停止工作了。

我如何“更新”此绑定?

谢谢。

1个回答

12
Ext.select 选择所有元素并在此时静态地添加单击处理程序。如果要使新元素具有相同的处理程序,则必须在创建它们之后将其添加到它们中。然而,这不是最佳方法。
在这种情况下最好使用事件委托-向容器元素添加单个单击处理程序,然后根据所单击的项委派处理过程。这更有效(只需要一个事件处理程序函数),并且更加灵活。例如,如果您的包含元素具有id“gallery-ct”,则应该如下所示:
Ext.onReady(function() {
    Ext.get('gallery-ct').on('click', function(e, t){
      // t is the event target, i.e. the clicked item.
      // test to see if it is an item of the type you want to handle
      // (it is a DOM node so first convert to an Element)
      t = Ext.get(t);
      if(t.hasClass('gallery-item'){
        // radioClass automatically adds a class to the Element
        // and removes it from all siblings in one shot
        t.radioClass('gallery-item-selected');
      }
    });
});

编辑:如果您的点击目标中可能包含嵌套项,则需要采取略微(但不多)更高级的方法,并在从单击元素冒泡的过程中查找目标(使用EventObject.getTarget)。如果您的目标在事件链中随着单击元素冒泡而来,那么您就知道它仍然是有效的单击。更新的代码:

Ext.onReady(function() {
    Ext.get('gallery-ct').on('click', function(e, t){
      // disregard 't' in this case -- it could be a child element.
      // instead check the event's getTarget method which will 
      // return a reference to any matching element within the range
      // of bubbling (the second param is the range).  the true param 
      // is to return a full Ext.Element instead of a DOM node
      t = e.getTarget('.gallery-item', 3, true);
      if(t){
        // if t is non-null, you know a matching el was found
        t.radioClass('gallery-item-selected');
      }
    });
});

非常感谢。经过一些小调整,我已经使它适合我的需求了。有一些行为让我感到奇怪的是,在gallery-item div内点击图像不会触发gallery-item click事件。 - babadbee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接