首页 > Web开发 > 详细

关于MVC设计模式

时间:2015-10-26 13:36:58      阅读:205      评论:0      收藏:0      [点我收藏+]

关于MVC设计模式;

对于如下一串代码

<select id="setAnimal">
     <option value="cat">cat</option>
     <option value="fish">fish</option>
     <option value="bird">bird</option>
 </select>
 <p id="whatDoesThisAnimalDo"></p>

想实现选项卡选择数据对<p>标签的实时更新

简单的编程方法

var setAnimal=document.getelementById("setAnimal");
var whatDoesThisAnimalDo=document.getelementById("whatDoesThisAnimalDo");

setAnimal.onchange=function(){
    this.animalDO=null;
    switch(this.value){
    case "cat":
        this.animalDO="cat do!";break;
    case "fish":
        this.animalDO="fish swimming!";break;
    case "bird":
        this.animalDO="bird do!";break;
    default:
        this.animalDO="wang";
    }
    whatDoesThisAnimalDo.innerHTML="this.animalDO";
}

MVC的实现方法

    //controller
    var AnimalDo={
        start:function(){
            AnimalDo.view.start()
        },
        set:function(value){
            this.model.setAnimal(value);

        }

    };

    AnimalDo.model={
        //数据字典
        animalDictionary:{
            cat:"cat do!",
            fish:"fish swimming!",
            bird:"bird do!"
        },
        //当前数据
        currentAnimal: null,
        //更改当前数据,在更改数据或者从数据字典中获取数据时,一点要做验证
        //每一次currentAnimal改变时,会通知view进行更新
        setAnimal:function(name){

            this.currentAnimal=this.animalDictionary[name]?name:null;
            //console.log("传进来的值"+name+"---"+"this.currentAnimal"+this.currentAnimal);
            AnimalDo.view.update();
        },
        getCurrentAnimal:function(){
            return this.currentAnimal?this.currentAnimal + " " + this.animalDictionary[this.currentAnimal] :"no Animal";
        }

    };
    AnimalDo.view={
        //将用户操作反馈至视图层的onchange上
        start:function(){
            this.id=document.getElementById("setAnimal");
            console.log(this.id.value);
            this.id.onchange=this.onchange;
        },
        onchange:function(){

            AnimalDo.set(this.value);//一定要注意此函数中的this指的是document.getElementById("setAnimal"),即是上个函数的this.id
        },
        update:function(){
            this.p=document.getElementById("whatDoesThisAnimalDo");
            this.p.innerHTML=AnimalDo.model.getCurrentAnimal();
        }
    };

    AnimalDo.start();

 

关于MVC设计模式

原文:http://www.cnblogs.com/windSamW/p/4910865.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!