前端越来越重,原来那种意大利面似的代码显得越来越难以维护。
重构势在必行,初步方案我选定backbone.js 作为javascript mvc框架。如果说原因,我觉得一个方面是由于它的轻量级,另外,就是它不像ember.js 绑定ui视图,灵活性更大一些。
鉴于有同学没有接触过javascript mvc模式,我写了两个小例子:
第一个是:没有使用mvc模式的:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>javascript demo no mvc</title>
</head>
<body>
<h3>JavaScript no MVC</h3>
<div>
<select name="" id="setAnimal">
<option value="cat">cat</option>
<option value="fish">fish</option>
<option value="bird">bird</option>
</select>
<p id="whatDoesThisAnimalDo"></p>
</div>
<script type="text/javascript">
document.getElementById('setAnimal').onchange = function(){
var thisAnimalDoes;
switch(this.value){
case 'cat':
thisAnimalDoes = 'cat meows';
break;
case 'fish':
thisAnimalDoes = 'fish swims';
break;
case 'bird':
thisAnimalDoes = 'bird fies';
break;
default:
thisAnimalDoes = 'wuff?';
}
document.getElementById('whatDoesThisAnimalDo').innerHTML = thisAnimalDoes;
};
</script>
</body>
</html>
第二个例子: 采用mvc模式
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>javascript demo mvc</title>
</head>
<body>
<h3>JavaScript simple MVC</h3>
<div>
<select name="" id="setAnimal">
<option value="cat">cat</option>
<option value="fish">fish</option>
<option value="bird">bird</option>
</select>
<p id="whatDoesThisAnimalDo"></p>
</div>
<script type="text/javascript">
// controller
Animal = {
start: function(){
this.view.start();
},
set: function(animalName){
this.model.setAnimal(animalName);
}
};
// model
Animal.model = {
animalDictionary :{
cat: 'meows',
fish: 'swims',
bird: 'flies'
},
currentAnimal:null,
setAnimal: function(animalName){
this.currentAnimal = this.animalDictionary[animalName]?animalName:null;
this.onchange();
},
onchange: function(){
Animal.view.update();
},
getAnimalAction: function(){
return this.currentAnimal ? this.currentAnimal + " " + this.animalDictionary[this.currentAnimal] : 'wuff?';
}
};
// view
Animal.view = {
start: function(){
document.getElementById('setAnimal').onchange = this.onchange;
},
onchange: function(){
Animal.set(document.getElementById('setAnimal').value);
},
update: function(){
document.getElementById('whatDoesThisAnimalDo').innerHTML = Animal.model.getAnimalAction();
}
};
Animal.start();
</script>
</body>
</html>
第二个例子中,进行了简单的mvc分层,看似代码量比第一种多了许多,但是对于后期模块的维护还是有很大的好处的。