视图渲染时触发多个事件
我正在使用 Backbone.js 构建一个应用程序,但是我遇到了一个无法尽早解决的问题。
我现在有一个简单的列表/详细视图设置,但每次渲染详细视图时,我的事件都会变得复杂。例如,显示两个详细视图并单击链接将导致其被单击两次。
我的视图看起来像这样(用 CoffeeScript 编写):
#
# Project List View
#
class ProjectListView extends Backbone.View
el: $("#projectList")
events : {
"click #addProject" : "createNewProject"
}
initialize : ->
@template = _.template(app.projectListView)
_.bindAll(this, "render", "createNewProject")
@render()
createNewProject : (e) ->
e.preventDefault()
e.stopPropagation()
tempProject = Projects.create({
title : 'Test Project'
description : ''
browserDefault : 12
lineHeight : 21
})
render : =>
$(@el).html(@template())
@delegateEvents()
return @
显然,事件已经结束,我没有触发任何点击事件。我在这里缺少什么?
I'm building an app using Backbone.js however I have run into a problem that I can't fix very early on.
I have a simple list / detail view setup right now but everytime I render the detail view my events are compounded. Eg show two detail views and clicking a link will cause it to be clicked twice.
My view looks like this (written in CoffeeScript):
#
# Project List View
#
class ProjectListView extends Backbone.View
el: $("#projectList")
events : {
"click #addProject" : "createNewProject"
}
initialize : ->
@template = _.template(app.projectListView)
_.bindAll(this, "render", "createNewProject")
@render()
createNewProject : (e) ->
e.preventDefault()
e.stopPropagation()
tempProject = Projects.create({
title : 'Test Project'
description : ''
browserDefault : 12
lineHeight : 21
})
render : =>
$(@el).html(@template())
@delegateEvents()
return @
Obviously take the events has out and I don't get any clicks events firing. What am I missing here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您粘贴的代码似乎没有正确缩进。本来就是这样吗?
您不需要
_.bindAll
行。相反,只需使用=>
来定义您的方法(而不是->
)我做了一些风格上的更改并取出了额外的
@delegateEvents
,正如朱利安建议的那样。看看这是否有效:The code you pasted in doesn't appear to be indented properly. Is that how it was originally?
You don't need the
_.bindAll
line. Instead, just use=>
to define your methods (instead of->
)I made some stylistic changes and took out the extra
@delegateEvents
, as Julien suggested. See if this works:这是我对您的代码的评论。 Backbone 将根据您的事件选项自动委托事件(使用 delegateEvents)。您不必在渲染函数中执行此操作(很可能是向您抛出双重事件的原因)。从渲染中删除deleteEvents。
另外,@el 已经定义为 jQuery 对象,因此您不必在渲染中再次执行此操作。
您将创建 2 个项目列表视图吗?如果是这样,id 必须是唯一的...
Here are my comments on your code. Backbone will automatically delegate the events (using delegateEvents) based on your events option. You do not have to do it in the render function (most probably the cause of double events thrown at you). Remove deleteEvents from your render.
Also, @el is already defined as a jQuery object, so you do not have to do it again within your render.
Will you be creating 2 project list views? If so ids must be unique...