I am right now developing a dead simple application using backbonejs mvc javascript library.Just to show how simple it is here is the html
Sample Html
<div class="container">
<div>
<label>
Name:
<input id="txtName" type="text" title="Type your name please" /></label>
<button id="btnSubmit" type="button" value="Submit">
Submit</button>
</div>
<div id="names">
</div>
</div>
Operation
Here’s all i want the application to do.
-
User Types a name(or some alphanumeric string) and clicks submit.
-
The value(which is what they call model i suppose) after validation will be sent to restful service.
-
Service will return the same string along with status of database save operation.
I am now confused as to where the click event will handled(is it in the model?), after that where should the render method be called?(is it in views). Below you will find the script i had managed up until now
Model.js
//store a global reference to model
window["model"] = Backbone.Model.extend({
defaults: { name: "Type your name"
},
validate: function () {
}
});
View.js
//store a global reference to view
window["view"] = Backbone.View.extend({});
nothing in the view to say 🙁
Application.js
//when every thing is ready kick of the application
$(document).ready(function () {
var modelInstance = new model();
});
-
so do i add click event to the button in application.js or model.js.which is the convention/best practice?
-
Will it be possible for me to render the names collection returned from service into
#namesand status of the database insertion into anotherdivsomewhere up above the container? Can the view render both views?
So, here is a disclaimer: If this is all your app is doing, then Backbone is way too much ceremony. When the app gets more complex with more moving parts, Backbone becomes pretty amazing.
That being said, I have created a jsFiddle to highlight how you might use Backbone for what you want to do: http://jsfiddle.net/BrianGenisio/CZwnk/4/
Basically, you have a
Personmodel and aPeoplecollection to hold thePersonmodels. You then have three views:NewPersonViewwhich is the form for entering your data, which is responsible for adding new items to thePeoplecollection. Then you have aPeopleViewview which is responsible for showingPeoplecollection, which will watch the collection and show any additions. Finally, is thePersonViewwhich is responsible for showing an individualPersonmodel.When it all comes together, it looks a little something like this:
HTML:
JavaScript