我遇到了使用backbone.js的盲点。我写了这段代码,而我想要做的就是得到
按钮点击时渲染的测试div。如果我在render()
函数中调用initialize()
,它会进行渲染。
但是,我从不触发render()
函数来响应click事件。
我错过了什么?
谢谢!
HTML容器
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<!-- / Always force latest IE rendering engine (even in intranet) & Chrome Frame -->
<meta content='IE=edge,chrome=1' />
<meta http-equiv='X-UA-Compatible' />
<link type="text/css" rel="stylesheet" href="/stylesheets/site.css" media="screen" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script type="text/javascript" src="/javascripts/underscore-min.js"></script>
<script type="text/javascript" src="/javascripts/backbone-min.js"></script>
<script type="text/javascript" src="/javascripts/application.js"></script>
<script type="text/javascript" src="/javascripts/sample_data.js"></script>
<title>The Middleman!</title>
</head>
<body class='page_classes'>
<div id='main' role='main'>
<h1>The Middleman is watching.</h1>
<div id='band-app'>
<button id='new-band'>new band</button>
</div>
</div>
</body>
</html>
SAMPLE_TEMPLATE = """
<div id="my-fine-id">
My fine id!!!
</div>
"""
$ ->
class AppView extends Backbone.View
render: ->
console.log "rendering"
@template = _.template SAMPLE_TEMPLATE, {}
@el.html @template
initialize: ->
console.log "constructing"
@el = $('#band-app')
@events = {"click button#new-band": "render"}
app = new AppView()
答案 0 :(得分:1)
马吕斯说的是对的。
通常,您希望在类定义中指定events
,而不是在初始化程序中指定。实际上,对于此示例,您根本不需要initialize
函数:
class AppView extends Backbone.View
events:
'click button': 'render'
render: ->
@$el.html _.template SAMPLE_TEMPLATE, {}
$ ->
new AppView el:$('#band-app')
答案 1 :(得分:0)
我认为设置事件处理的delegateEvents
会在调用View
之前在initialize
构造函数中调用,因此要么在initialize
中明确地调用它方法(在设置events
地图后),或确保events
地图是作为构建View
类本身的一部分而设置的,请参阅: