backbone.jsHow do I implement a Backbone.js MVC example?
To implement a Backbone.js MVC example, first create a simple HTML page with a script tag to include the Backbone.js library:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
</head>
<body>
</body>
</html>
Then, create a basic Model, View, and Collection with the following code blocks:
Model:
var UserModel = Backbone.Model.extend({
defaults: {
name: '',
age: 0
}
});
View:
var UserView = Backbone.View.extend({
tagName: 'li',
render: function() {
this.$el.html(this.model.get('name') + ' (' + this.model.get('age') + ')');
return this;
}
});
Collection:
var UserCollection = Backbone.Collection.extend({
model: UserModel
});
Finally, instantiate the Model, View, and Collection, and render the View:
var user = new UserModel({name: 'John', age: 25});
var userView = new UserView({model: user});
var userCollection = new UserCollection([user]);
$('body').html(userView.render().el);
Output example
<li>John (25)</li>
Code explanation
- HTML page to include Backbone.js library
- Model: UserModel
- View: UserView
- Collection: UserCollection
- Instantiation of Model, View, and Collection
- Rendering of View
Helpful links
More of Backbone.js
- How do I use backbone.js to zip a file?
- ¿Cuáles son las ventajas y desventajas de usar Backbone.js para el desarrollo de software?
- How can I use Backbone.js with React to build a web application?
- How can I create a WordPress website using Backbone.js?
- How do I use a template engine with Backbone.js?
- How can I use Backbone.js to customize a WordPress website?
- How do I use Backbone.js to determine where something is?
- How do I use W3Schools to learn Backbone.js?
- How do I create tabs using Backbone.js?
- How can I update my Backbone.js application?
See more codes...