MVC小例子

一个mvc的在线小实例

MVC

1
<div id="app"></div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const view ={
el:'#app',
template:'',
render(lists){
this.template += `<ul>`;
$(lists).each((index,list) => {
this.template += `<li style="border-bottom:1px solid red;>
<div class=title>${list.title}</div>
<div class=author>作者:${list.author.loginname}</div>
</li>`;
});
this.template += `<ul>`;
$(this.el).html(this.template);
}
};
const model = {
lists:[],
getLists(){
return $.get('https://cnodejs.org/api/v1/topics',({data})=>{this.lists = data;});
}
};
const controller = {
init(view,model){
this.view = view;
this.model = model;
this.model.getLists().then(()=> this.view.render(this.model.lists));
this.bindEvents();
},
bindEvents(){
this.handleClick();
},
handleClick(){
$(this.view.el).on('click', '.title', ev => {
ev.target.style.color = 'red;
});
}
};
controller.init(view,model);

JS Bin

踩坑

1
2
<div class=title>${list.title}</div>
<div class=author>作者:${list.author.loginname}</div>

在模板字符串中,
写成双引号class="title"会渲染成class=" title",当中有个空格,不知什么原因(:з」∠)
因此,建议写成没有引号class=title,或者单引号class='title'

-------------本文结束感谢您的阅读-------------