1.背景
在這個暑假,我做了一個使用HTML5,CSS3和JS完成的應用,它可以在PC端和各個移動端運行。應用中的動態效果主要是靠JS實現,由於對JS的不熟悉,造成了一系列問題。最主要的問題在於代碼的組織。隨着代碼越寫越多,代碼顯得非常雜亂無章,對於後期的維護和添加新的功能非常不利。於是我求助與公司的技術總監,他告訴我應該學會組織自己的代碼,可以使用MVC的設計模式。於是我在網上找了一些了的例子,其中有一篇博文(http://alexatnet.com/articles/model-view-controller-mvc-javascript)描述的非常好,但是這篇博文中存在一些弊端。我將以此博文爲起點,談下我對javascript MVC的認識。
2.實現目標
3.簡單的實現方式
html文件
<!doctype html>
<html>
<!--head-->
<head>
<meta charset="utf-8">
<title>List</title>
<link rel="stylesheet" href="main.css">
</head>
<!--body-->
<body>
<div id='container'>
<div id='content_container'>
<ul id='items'>
<li class='item'>Python</li>
<li class='item'>PHP</li>
<li class='item'>Javascript</li>
<li class='item'>HTML5</li>
</ul>
</div>
<div id='btn_container'>
<button class = 'btn' id='btn_add'>+</button>
<button class = 'btn' id='btn_del'>-</button>
</div>
</div>
</body>
<script src="lib/jquery.js" type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function() {
$('#btn_add').bind('click',function(){
console.log('add button click!');
var value = prompt('input the value:', '');
if(value)
$('#items').append("<li class='item'>"+value+"</li>");
});
$('#btn_del').bind('click',function(){
console.log('delete button click!');
if($('.item').length){
var del = confirm('you want delete it?')
if(del)$('.item:last').remove();
};
});
});
</script>
</html>
css文件*{margin: 0px;padding: 0px;}
body { background-color: #E7EBF2; font-family:arial; font-size:13px }
#container{
width: 330px;
margin:0 auto;
min-height: 200px;
border:solid 1px #B4BBCD;
overflow: hidden;
}
#content_container{
width:250px;
min-height: 100px;
margin:20px 10px 20px 10px;
float:left;
border:solid 1px #B4BBCD;
}
#btn_container{
width:40px;
margin-top: 25px;
float: left;
}
.btn{
width:30px;
height:30px;
margin:5px;
float: left;
}
.item{
list-style: none;
margin:5px 4px 4px 5px;
font-size: 20px;
}
效果
首先構建html頁面,裏面包括一個contaniner,爲大的容器,然後裏面有content_container和btn_container分別對應着內容和按鈕容器。