According to Thomas Davis Backbone views are used to reflect what your applications' data models look like. They are also used to listen to events and react accordingly.
Introduction
In this article we will see implementation of view in
Backbone.js..Objective
The Objective of the article is to focus on view functionality and how to use views with a Javascript templating library
In order to implement Backbone.js we have to add
jquery because backbone needs Jquery or some other DOM library
Using the code
Here we had a container with a sample stuff and a template for adding into container...
we had a sample model with data..
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<style type="text/css">
#container {
padding: 20px;
border: 1px solid #333;
width: 400px;
}
#list-template {
display: none;
}
</style>
<script type="text/javascript" src="backbone/Jquery.js"></script>
<script type="text/javascript" src="backbone/backbone-min.js"></script>
<script type="text/javascript" src="backbone/underscore-min.js"></script>
</head>
<body>
<div id="container">
<button>Load</button>
<ul id="list">
</ul>
</div>
<div id="list-template">
<li><a href=""></a></li>
</div>
<form id="form1" runat="server">
<script>
model = new Backbone.Model({
data: [
{ text: "Dotnetfunda", href: "http://dotnetfunda.com" },
{ text: "itfunda", href: "http://itfunda.com/" },
{ text: "kidsfunda", href: "http://kidsfunda.com" }
]
});
var View = Backbone.View.extend({
initialize: function () {
console.log('initializing');
}
});
var view = new View();
</script>
</form>
</body>
</html>
Here is sample output
Passing Options
Here we have send a blankoption which is directly accessible by this.options
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<style type="text/css">
#container {
padding: 20px;
border: 1px solid #f00;
width: 400px;
}
#list-template {
display: none;
}
</style>
<script type="text/javascript" src="backbone/Jquery.js"></script>
<script type="text/javascript" src="backbone/backbone-min.js"></script>
<script type="text/javascript" src="backbone/underscore-min.js"></script>
</head>
<body>
<div id="container">
<button>Load</button>
<ul id="list">
</ul>
</div>
<div id="list-template">
<li><a href=""></a></li>
</div>
<form id="form1" runat="server">
<script>
model = new Backbone.Model({
data: [
{ text: "Dotnetfunda", href: "http://dotnetfunda.com" },
{ text: "itfunda", href: "http://itfunda.com/" },
{ text: "kidsfunda", href: "http://kidsfunda.com" }
]
});
var View = Backbone.View.extend({
initialize: function () {
console.log(this.options.blankoption);
}
});
var view = new View({ blankoption: "empty string" });
</script>
</form>
</body>
</html>
Here is sample output