每个实例事件绑定的主干
我有一个视图,它为列表中的每个项目创建一个子视图。一般我们称它们为 ListView 和 ListItemView。我在 ListItemView 上附加了一个事件,如下所示:
events: {
"click .remove": "removeItem"
}
我有为 ListItemView 模板生成的 html,大约如下所示(将 lb/rb 交换为 {/},以便您可以看到“非法”html):
{div class="entry" data-id="this_list_item_id"}
SOME STUFF HERE
{div class="meta"}
{a class="remove" href="javascript:;"}[x]{/a}
{/div}
{/div}
问题是,当单击任何 [x],所有 ListItemView 都会触发其 removeItem 函数。如果我让它脱离这个模型的 id,那么我会删除页面上的所有项目。如果我让它离开被单击项目的父元素的父元素来获取数据 ID,我会删除每个 ListItemView 实例。有没有办法创建一个仅触发单个removeItem 的特定于实例的事件?
如果我让 ListView 持有 ListItemView 的单个实例并重新分配 ListItem 模型并渲染列表中的每个项目,则它可以工作。我最终只触发了一个操作(removeItem)。问题是,我必须找到点击目标的父级的父级才能找到 data-id attr。就我个人而言,我认为下面的代码片段相当丑陋,需要更好的方法。
var that = $($(el.target).parent()).parent();
任何人提供的任何帮助将不胜感激。
I have a view that creates a sub-view per item in the list. Generically let's call them ListView and ListItemView. I have attached an event as follows on ListItemView:
events: {
"click .remove": "removeItem"
}
I have template-generated html for ListItemView that is approximately like the following (swapped lb/rb for {/} so you can see the "illegal" html):
{div class="entry" data-id="this_list_item_id"}
SOME STUFF HERE
{div class="meta"}
{a class="remove" href="javascript:;"}[x]{/a}
{/div}
{/div}
The problem is, when the click on any of the [x]'s, ALL of the ListItemViews trigger their removeItem function. If I have it go off of this model's id, then I drop all the items on the page. If I have it go off the clicked item's parent's parent element to grab the data-id, I get a delete for EACH ListItemView instance. Is there a way to create an instance-specific event that would only trigger a single removeItem?
If I have ListView hold a single instance of ListItemView and reassign the ListItem model and render for each item in the list it works. I only end up with one action (removeItem) being triggered. The problem is, I have to find the click target's parent's parent to find the data-id attr. Personally, I think the below snippet is rather ugly and want a better way.
var that = $($(el.target).parent()).parent();
Any help anyone gives will be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来您的
events
哈希值位于您的 ListView 上。如果是,那么您可以将
events
哈希移动到 ListItemView,并且您的removeItem
函数可以是以下内容如果不是这种情况,您可以提供您的 ListView 和 ListItemView代码,以便我可以查看它。
It seems like your
events
hash is on your ListView.If it is, then you can move the
events
hash to ListItemView and yourremoveItem
function can be the followingIf this isn't the case, can you provide your ListView and ListItemView code so I can look at it.
这是一个疯狂的猜测,但也是有可能的;检查您渲染的 html 是否有效。由于 html 格式错误,dom 可能会陷入困境
A wild guess but possible; check that your rendered html is valid. It might be possible that the dom is getting in a tiz due to malformed html