视图对象类似与与<TextView/>对应的TextView对象,每个视图对象都对应一个dom元素。
我们在定义视图对象的时候,可以指定dom对象,存储在视图对象的el属性中,如果不指定,backbone.js会自动生成一个空的div元素赋值给el。
下面一个例子实现点击按钮改变div中文字的功能,展示一下视图对象如何使用:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>index.html</title>
<link rel="stylesheet" href="../jquery.mobile-1.0.1.min.css" />
<script type="text/javascript" charset="utf-8" src="../jquery.js"></script>
<script type="text/javascript" charset="utf-8" src="../jquery.mobile-1.0.1.min.js"></script>
<script type="text/javascript" charset="utf-8" src="../cordova-2.0.0.js" ></script>
<script type="text/javascript" charset="utf-8" src="../underscore-min.js"></script>
<script type="text/javascript" charset="utf-8" src="../backbone-min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
document.addEventListener("deviceready", onDeviceReady, false);
});
function onDeviceReady()
{
}
function createObject(){
var TestView=Backbone.View.extend({
initialize:function(){
},
render:function(){
$(this.el).html('div1');//将dom元素的文字设置为“div1”
}
});
var testView=new TestView({el: $("#textdiv")});//指定el属性为id是textdiv的dom元素
testView.render();
}
</script>
</head>
<body>
<!-- begin first page -->
<div id="page1" data-role="page" >
<header data-role="header"><h1>Hello World</h1></header>
<div data-role="content" class="content">
<div id="textdiv">HelloWorld</div></span>
<button type="button" οnclick="createObject()">Click Me!</button></span>
</ul>
</div>
<footer data-role="footer"><h1>Footer</h1></footer>
</div>
<!-- end first page -->
</body>
</html>