JS 實現MVC的寫法

來源:互聯網
上載者:User

標籤:java   io   art   cti   re   html   

案例:當select 下拉選擇框值變化時,顯示其值(不是文本)

常規寫法

<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="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="cat">cat</option>   <option value="fish">fish</option>   <option value="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>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.