50行代码仿backbone_todos

<!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>

  

posted @ 2014-03-24 14:25  方方和圆圆  阅读(295)  评论(0编辑  收藏  举报

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