Reputation: 5358
I found lots of questions for the same issue [events not being bound in view] and I was able to understand my mistakes and corrected it. Although the following code is not working. Actually I'm not understanding the concept of views in backbone.js. How does view bind with collections?
$(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();
});
This is my 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>
Expecting some good explanation on views
Upvotes: 0
Views: 1904
Reputation: 590
when you specify the el in the View it creates an el with that tag name rather than selecting the tag from the DOM . So if you send the el while initializing the View you would be able to bind events to any element in the passed el.
and using #text-input instead of button#text-input is more of a syntax thing , since the earlier one does not work but the latter one works
Upvotes: 1
Reputation: 590
you need to pass the el to the view
var body1 = document.getElementsByTagName('body');
var appview = new AppView({
el: body1
});
And apart form this you need to have the selector to bind the event as
events: {"click #text-input" : "newMsg"} ,
I am not sure about the underscore template you are using . But when i tried your code the template did not load. I use the mustache.js templates which is lot simpler .
Upvotes: 2