MVVM
axois
- 比jQuery.ajax功能更多
- 除了ajax功能之外,没有其他功能(更专注ajax)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
 34let book={ 
 name:'javascript 高级程序设计'
 number:2,
 id:1
 }
 //interceptors:在真正返回response之前使用
 axios.interceptors.response.use(function(response){
 let config=response.config
 let {method,url,data}=config //data是请求的data
 if(url==='/book/1'&&method==='get'){
 response.data=book
 }else if(url==='/book/1'&&method==='put'){
 Object.assign(book,data)
 /*Object.assign(obj,{}) Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。*/
 response.data=book
 }
 return response
 })
 /*上面是假的后台*/
 axios.get('/book/1').then((data)=>{
 let originalHtml=$('#app').html()
 let newHtml=originalHtml.replace('__name__',data.name).replace('__number__',data.number)
 $('#app').html(newHtml)
 })
 $('#app').on('click','#addOne',function(){
 var oldNumber=$('#number').text()
 var newNumber=oldNumber-0+1
 axios.put('/book/1',{
 number:newNumber
 }).then(function(){
 $('#number').text(newNumber)
 })
 })
意大利面条式代码,是软件工程中反面模式的一种,是指一个源代码的控制流程复杂、混乱而难以理解,尤其是用了很多GOTO、例外、线程、或其他无组织的分支。
| 1 | fakeData() | 
用MVC改写代码
| 1 | ``` | 
用构造函数重写Model和view1
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68function Model(options){
    this.data=options.data
    this.resource=options.resource
}
Model.prototype.fetch=function(id){
    return axios.axios.get(`/book/${id}`).then((response)=>{
    this.data=response.data
    return response
    })
}
Model.prototype.update=function(data){
    let id=this.data.id
    return axios.put(`/${this.resource}s/${id}`,data).then((response)=>{
    this.data=response.data
    return response
    })
}
//--------上面是MVC类,下面是MVC对象------------//
let bookModel=new Model({
    data:{
    name:'',
    number:0,
    id:''
    }
    resource:'book'
    })
let view=new Vue({
    el:'#app',
    data:{
        book:{
        name:'',
        number:0,
        id:''
       },
       n:1
    },
    template:
    <div>
        <div>
        书名:《{{book.name}}》
        数量:<span id=number>{{book.number}}</span>
        </div>
        <div>
            <input v-model="n"/>
        </div>
        <div>
            <button v-on:click="addOne">加1</button>
        </div>
    </div>
    ,
    created(){
    model.fetch(1).then(()=>{
      this.book=model.data
    })
 },
    method:{
    addOne(){
        model.updata({
        number:this.book.number+(this.n-0)
        }).then(function(){
        this.view.book=this.model.data
            })
        }
   }
})
用VUE代替view,去除controller
双向绑定


| 1 | //ES6技巧 | 
| 1 | $('#app').on('click','#addOne',function(){}) | 
Comments