美文网首页
achieve the pattern of MVC simpl

achieve the pattern of MVC simpl

作者: Komolei | 来源:发表于2017-11-20 15:10 被阅读0次

What's the MVC?

  1. the mvc pattern is that the view is separate from the data using the controller controls the input or output of data.
  2. the controller .It's get data from the data layer and handle the data. Finally,the view layer to display the data of the controller provide.

How to achieve the MVC pattern in the js?

Follow me~

the instructor of the html

//<div class='module'>
//  <input type='text'> 
//  <button>click</button>
//</div>
<div class='module'>
</div>
<script id='template'>
    <input type='text'> 
    <button>click</button>
</script>
  1. look this directive program
let a=document.querySelector('input');
a.addEventListener('click',()=>console.log('this is a'))
  1. use declaration
let options={
  el:'el',
  data:{
    _data:''},
  template:'#template'
  events:{
      //'change input':function(){
         // console.log('change')},
      'change input':'addToCart',
     // 'click button':function(){
     //     console.log('click')}}
        'click button':'btnClick'
    },
    btnClick:funciton(){
      console.log("click");
      let val=document.querySelector('input').value;
      this.append(val);
      },
    addToCart:function(){
        console.log('add to shopCart')
      },
    render:function(){
       document.querySelector(this.el).innerHTML= document.querySelector(this.template).innerHTML;
    }
}
new class Controller(options){
    constructor(options){
      this.el=options.el;
      //this.event=options.event;
      for(let key in options)
        { 
          this[key]=options[key];
        }
       if(this.template & this.render){
                this.render()
            }
      this.bindEvent();
    }

   append(val){
         let div=document.createElement('div');
         div.innerText=val;
         document.querySelector(this.el).appendChild(div);
    }
    bindEvent(){
        for(let item in this.events){
            let parts=item.split(' ');
            let eventType=parts.shift();
            let selector=parts.join('');
            if(typeof this.event[item] ==='funciton'){
                document.querySelector(this.el).addEventListener(eventType,this.event[item]);
            }else if(typeof this.event[item]==='string'){
                document.querySelector(this.el).addEventListener(eventType,this[this.event[item]].bind(this));
          }
}

now You can see the pattern of MVC 。
demo;

相关文章

网友评论

      本文标题:achieve the pattern of MVC simpl

      本文链接:https://www.haomeiwen.com/subject/hmdvvxtx.html