【发布时间】:2012-10-15 12:45:25
【问题描述】:
我有以下 HTML:
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Description</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Item 1</td>
<td>Description of Item 1</td>
<td>
<a href="#" data-action="edit" data-item-id="1">Edit</a>
<a href="#" data-action="delete" data-item-id="1">Delete</a>
</td>
</tr>
<tr>
<td>2</td>
<td>Item 2</td>
<td>Description of Item 2</td>
<td>
<a href="#" data-action="edit" data-item-id="2">Edit</a>
<a href="#" data-action="delete" data-item-id="2">Delete</a>
</td>
</tr>
</tbody>
</table>
动态添加表格行 (tr elements)。
我将点击事件连接到所有Edit 链接,如下所示:
void wireUpTableEvents() {
var editLinks = queryAll('#order-items table tbody [data-action="edit"]');
editLinks.forEach((element) {
element.on.click.add((event){
print(element.attributes['data-item-id']);
});
});
}
如上所述,表行 (tr elements) 是动态添加的,因此上述代码仅在我调用 wireUpEvents 之后我执行添加行的方法时才有效。
当将来动态添加元素时,有谁知道使用DART 的on.click.add() 向元素添加事件侦听器的语法或事件侦听器?
我尝试检查 DART 文档,但 documentation on Event Listeners 为空白。
如果我使用 jQuery,我可能会使用类似于:
$("#order-items table")on("click", "tbody [data-action="edit"]", function(){...})
...但我只想使用 DART 编写我的示例应用程序。
编辑
尽管future 听起来很适合回调,但对于我需要的东西来说似乎有点矫枉过正,因为在我的场景中没有长时间运行的任务。
我能够将事件侦听器附加到静态元素但处理未来子元素的点击事件的最接近方法是:
void wireUpTableEvents() {
var tableBody = query('#order-items table tbody');
// Attach Event Listener to the static tbody, which always exists.
tableBody.on.click.add((event) {
var clickedElement = event.srcElement;
var itemId = clickedElement.attributes['data-item-id'];
// Check if the clicked element was either one of the edit links or one of the delete links.
switch (clickedElement.attributes['data-action']) {
case 'edit':
// Replace print with calling a method to process edit request for this item.
print('processing edit click from item with id: $itemId');
break;
case 'delete':
// Replace print with calling a method to process delete request for this item.
print('processing delete click from item with id: $itemId');
break;
}
});
}
上面的代码可以在任何实际的tr 元素加载之前执行,并且在tr 元素加载之后在某个未知的后期阶段仍然有效。
我还发现它现在涵盖了任何动态添加的行、预加载的行以及其他为新记录动态添加的行等。
【问题讨论】:
-
我最终选择了我在问题编辑中添加的解决方案。它允许我将事件侦听器绑定到表一次,并通过使用事件冒泡和
event.srcElement属性来处理在任何阶段动态添加的任何新行中的任何点击事件。 -
我对否决票有点困惑。无论如何,如果这个问题没有表明任何研究工作不明确或无用,请随时这样做,不要害怕让我知道如何改进它!目前,否决票看起来是随机的和荒谬的。在提出问题时,有关该主题的可用文档不存在,并且指向它的链接现在甚至完全死了。随意发表评论并附上新文档的链接,因为我很想知道该问题的另一种解决方案。