What's the MVC?
- the mvc pattern is that the view is separate from the data using the controller controls the input or output of data.
- 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>
- look this directive program
let a=document.querySelector('input');
a.addEventListener('click',()=>console.log('this is a'))
- 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;
网友评论