试着mvc写一个文本输入并且下方展示文本的demo,代码:
//html:
<body></body>
//js:
class view{
constructor(){
this.input=document.createElement('input')
this.button=document.createElement('button')
this.button.innerText='clear'
this.div=document.createElement('div')
const body=document.body
body.append(this.input)
body.append(this.div,this.button)
}
inputFn(x){
this.input.addEventListener('input',x)
}
clear(d){
this.button.addEventListener('click',d)
}
render(text){
this.div.innerText=text
}
}
class model{
constructor(){
this.text=''
}
getText(x){
this.text=x
}
clear(){
this.text=''
}
}
class controll{
constructor(model,view){
this.model=model
this.view=view
this.view.inputFn(this.fn1)
this.view.clear(this.fn)
}
fn1=(e)=>{ //Uncaught SyntaxError: Unexpected token =
this.model.getText(e.target.value)
this.view.render(this.model.text)
}
fn=()=>{ //Uncaught SyntaxError: Unexpected token =
this.model.clear()
this.view.render(this.model.text)
}
}
new controll(new model(),new view())
上面fn,fn1会出现错误,如果直接写在constructor里面正常:
class controll{
constructor(model,view){
this.model=model
this.view=view
this.view.inputFn((e)=>{
this.model.getText(e.target.value)
this.view.render(this.model.text)
})
this.view.clear(()=>{
this.model.clear()
this.view.render(this.model.text)
})
}
请问是哪里出错?还是写的mvc思路错了?
类成员方法不是这样定义的。现在还不能用 xxx=... 的形式。