我发现了很多关于同一问题的问题[事件没有被绑定在视图中],我能够理解我的错误并纠正错误。尽管下面的代码不起作用。其实我并不了解backbone.js中的视图概念。视图如何与集合绑定?Backbone.js绑定事件
$(function() { // Whole function executes after dom load
var LeaveAMsg = Backbone.Model.extend({});
var MsgCollection = Backbone.Collection.extend({
model: LeaveAMsg
});
var messages = new MsgCollection();
var AppView = Backbone.View.extend({
el: "body",
events: {"click button#text-input" : "newMsg"} ,
newMsg: function() {
alert('hai');
var inputField = $('input[name=newMessageString]');
messages.create({content: inputField.val()});
inputField.val('');
this.render();
} ,
render: function() {
var content = this.model.get('content');
$('.test-div').html(_.template($('#item-template').html(), {content:this.model.content}));
},
initialize: function() {
}
});
var appview = new AppView();
});
这是我的HTML
<body>
<div class='finaltry'>
<input type='text' name='newMessageString' />
<input type='button' id='text-input' value='Clickme' />
</div>
<div class='test-div'>
</div>
<script type="text/template" id="item-template">
<div>
<font color='gray'> <%= content %> </font>
</div>
</script>
</body>
期待的看法
感谢您的答复。在我的代码中,我已经在扩展函数本身初始化了el,并且我提到了单击按钮#text-input作为我的事件选择器。我可以知道它与您的解决方案有何不同? – Tamil 2012-02-01 04:51:48