50行代码仿backbone_todos

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
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>模仿TODOS,写了一个todos</title>
<script src="../3.20/jquery.js"></script>
<script src="../3.20/underscore-1.1.6.js"></script>
<script src="../3.20/backbone.js"></script>
</head>
<body>
    <div id="app">
        <ul id="contain">
         
        </ul>
        <a href="###" class="delAll">dsdfelAll</a>
        <a href="###" class="addDefault">addDefault</a>
    </div>
<script type="text/template" id="personTpl">
    <li>
        <span><%=name%></span>
        <b><%=age%></b>
        <button>del</button>
        <a>add</a>
    </li>
</script>
</body>
<script>
var M = Backbone.Model.extend({
    defaults : {
        name : "qihao",
        age : 27
    }
});
var C = Backbone.Collection.extend({
    model : M
});
var c = new C;
 
var V1 = Backbone.View.extend({
    tagName : "li",
    initialize : function(){
    },
    events : {
        "click button" : "destory",
        "click a" : "addOne"
    },
    tpl : _.template( $("#personTpl").html() ),
    render : function(){
        $(this.el).html( this.tpl( this.model.toJSON() ) )
        return this;
    },
    destory : function(){
        c.remove(this.model)
    },
    addOne : function(){
        var name = prompt("name");
        var age = prompt("age");
        c.add(new M({name : name ,age : age}));
    }
});
var V2 = Backbone.View.extend({
    el : $("#app"),
    events : {
        "click .delAll" : "delAll",
        "click .addDefault" : "addDefault"
    },
    initialize : function(){
        this.c = c;
        //数据模型的绑定this,要这样用才行;
        c.bind("all",this.renderAll,this)
    },
    renderAll : function(){
        this.el.find("#contain").html(" ");
        var _this = this;
        this.c.each(function(m){
            _this.renderSingal(m)
        });
    },
    renderSingal : function(m){
        this.el.find("#contain").append( (new V1({model : m})).render().el )
    },
    delAll : function(){
        this.el.find("#contain").html(" ");
    },
    addDefault : function(){
        this.renderSingal( new M )
    }
});
 
c.add( new M({name : "a", age  : 2}) );
c.add( new M());
var v2 = new V2()
v2.renderAll()
</script>
</html>

  

本文作者:方方和圆圆

本文链接:https://www.cnblogs.com/diligenceday/p/3620769.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   方方和圆圆  阅读(296)  评论(0编辑  收藏  举报

再过一百年, 我会在哪里?

💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起
点击右上角即可分享
微信分享提示