首页 > 代码库 > JS 实现MVC的写法
JS 实现MVC的写法
案例:当select 下拉选择框值变化时,显示其值(不是文本)
常规写法
<h3>JavaScript no MVC</h3> <div> <select name="" id="setAnimal"> <option value="http://www.mamicode.com/cat">cat</option> <option value="http://www.mamicode.com/fish">fish</option> <option value="http://www.mamicode.com/bird">bird</option> </select> <p id="animalAction"></p> </div> <script type="text/javascript"> var animal = document.getElementById(‘setAnimal‘); console.dir(animal); animal.onchange = function() { var action = null; switch (this.value) { case ‘cat‘: action = ‘cat meows‘; break; case ‘fish‘: action = ‘fish swim‘; break; case ‘bird‘: action = ‘bird fly‘; break; default: action = ‘unknow‘; } console.log(action); document.getElementById(‘animalAction‘).innerHTML = action; }; </script>
MVC 写法
<h3>javascript simple MVC</h3> <div> <select name="" id="setAnimal"> <option value="http://www.mamicode.com/cat">cat</option> <option value="http://www.mamicode.com/fish">fish</option> <option value="http://www.mamicode.com/bird">bird</option> </select> </div> <p id="animalDo"></p> <script> // controller Animal = { start : function() { this.view.start();//从视图触发 }, set : function(animalName) { this.model.setAnimal(animalName); //controller 改变 model } }; // model Animal.model = { animalDictionary : { car : ‘meows‘, fish : ‘swims‘, bird : ‘flies‘ }, currentAnimal : null, setAnimal : function(name) { this.currentAnimal = this.animalDictionary[name] ? name : null; this.onchange(); }, onchange : function() { Animal.view.update(); //model传递结果到View(个人觉得这里可以由Controller来专递,最好不要直接操作视图) }, getAnimalAction : function() { return this.currentAnimal ? this.currentAnimal + ‘ ‘ + this.animalDictionary[this.currentAnimal] : ‘unknow‘; } }; // view Animal.view = { start : function() { document.getElementById(‘setAnimal‘).onchange = this.onchange; //视图绑定事件 }, onchange : function() { Animal.set(document.getElementById(‘setAnimal‘).value); //视图执行操作,调用Controller }, update : function() { //视图执行最后的更新响应 console.log(Animal.model.getAnimalAction()); document.getElementById(‘animalDo‘).innerHTML = Animal.model.getAnimalAction(); } }; Animal.start();//入口 </script>
JS 实现MVC的写法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。