Backbone快速入门-了解的4个关键概念

1 篇文章 0 订阅
1 篇文章 0 订阅

Backbone快速入门-了解的4个关键概念

 

4个关键概念, model, collection, view, router:

  • 1. model

       定义model类,举例:
World = Backbone.Model.extend({
		//创建一个World的对象,拥有name属性
		name: null
});
  • 2. collection

          定义 model collection类, 举例:
Worlds = Backbone.Collection.extend({
                //集合对象构造函数
		initialize: function (models, options) {
			//**Key point 1**: 绑定view的addOneWorld方法到当前worlds集合对象的add动作
			//Purpose:当model数据变化时,触发view中的方法,从而可以更新View
			this.bind("add", options.view.addOneWorld);
		}
});
  • 3. view

  •  定义View类,举例:

        

	AppView = Backbone.View.extend({
		el: $("body"),
		
        //构造函数
		initialize: function () {
			//* 绑定Model,实例化一个Model集合类,并且以字典方式传入AppView的对象
			this.worlds = new Worlds(null, { view : this });

			//* 初始化渲染
			this.render();
		},

        //* 加载模板
		render:function(){
			//使用underscore这个库,来编译模板 
			
			//***Key Point 3: 从当前页面加载模板
			var template1=_.template($("#area1_template").html(),{hello:"Hello! You are welcome! "});
			//加载模板到对应的el属性中
			$("#area1").html(template1);

			//从外部文件加载模板
			//var template2=_.template($("#area2_template").html(),{footer:"Footer text~~~~"}); 
			//$("#area2").html(template2);
		},

		//* 事件绑定
		events: {
			//***Key Point 2: 绑定Dom中id为check的元素
			//Purpose:事件对应到代码处理,更新model数据, 从而联系到Key point 1
			"click #check": "checkIn",
		},
		
        //* 业务处理 (处理Model数据)
		checkIn: function () {
			var world_name = prompt("请问,您是哪星人?");
			if(world_name == "")
				world_name = '未知';

			var world = new World({ name: world_name });
			this.worlds.add(world);
		},

		//* View更新
		addOneWorld: function(model) {
			$("#world-list").append("<li>这里是来自<b>" + model.get('name') + "</b>星球的问候:hello world!</li>");
		}
	});

	//实例化AppView
	var appview = new AppView();

 

        注: 在View类中一般处理以下事情:

             1)  绑定Model (数据)

             2)  绑定Model

             3)  加载模板

             4)  事件绑定

             5)  业务处理 (处理Model数据)

             6)  View更新

             7)页面数据的变化同步到服务器端?


  • 4. router

        Backbone中的router, 有路由的意思,控制相应url的action, 扮演一部分MVC中Controller的角色。Backbone.Router会把你连接中的#标签当做是url路径。

	// 3. 定义MVC中的Controller部分 *****
	var AppRouter=Backbone.Router.extend({
		routes:{
			'posts/:id' : 'getPost',  //对应的链接为<a href="#/posts/120">Post 120</a>
		    'download/*path':'downloadFile',//对应的链接为<a href="#/download/user/images/hey.gif">download gif</a>
		    ':route/:action':'loadView', //对应的链接为<a href="#/dashboard/graph">Load Route/Action View</a>
		    '*actions' : 'defaultRoute'
		},


		getPost : function(id){
			console.log('id=' + id);
			alert(id);
		},
		
		downloadFile : function(path){
			alert(path);	// user/images/hey.gif
		},

		loadView : function(route,action){
			alert(route+"_"+action);	// dashboard_graph
		},
		
		defaultRoute : function(actions){
		    alert("Default " + actions);
		}
	});
	//实例化AppRouter
	var app_router=new AppRouter;
	Backbone.history.start();

 

        

 

完整源代码如下:

<!DOCTYPE html>
<html>
<head>
<title>Hill is struggling for his dream! </title>
</head>
<body>
<a href="#/posts/120">Post 120</a>
<a href="#/download/user/images/hey.gif">download gif</a>
<a href="#/dashboard/graph">Load Route/Action View</a>

<div id="area1"></div>
<div id="area2"></div>

<script type="text/template" id="area1_template">
	<label><%=hello%></label><br>

	<button id="check">报到</button>
	<ul id="world-list"></ul>
</script>
<!--<script src="template/area2_template.js"></script>-->
</body>

<script type="text/javascript" src="js/lib/jquery-1.8.2.js"></script>
<script type="text/javascript" src="js/lib/jquery-ui-1.9.0.js"></script>
<script type="text/javascript" src="js/lib/underscore-min-1.3.3.js"></script>
<script type="text/javascript" src="js/lib/backbone-min-0.9.10.js"></script>

<script>
(function ($) {
	// 1. 定义MVC中的Mobel部分 *****
	World = Backbone.Model.extend({
		//创建一个World的对象,拥有name属性
		name: null
	});
	
	Worlds = Backbone.Collection.extend({
		//World对象的集合
		initialize: function (models, options) {
			//***Key Point 1: 绑定view的addOneWorld方法到当前worlds集合对象的add动作
			//Purpose:当model数据变化时,触发view中的方法,从而可以更新View
			this.bind("add", options.view.addOneWorld);
		}
	});

	// 2. 定义MVC中的View部分 *****
	AppView = Backbone.View.extend({
		el: $("body"),
		
        //构造函数
		initialize: function () {
			//* 绑定Model,实例化一个Model集合类,并且以字典方式传入AppView的对象
			this.worlds = new Worlds(null, { view : this });

			//* 初始化渲染
			this.render();
		},

        //* 加载模板
		render:function(){
			//使用underscore这个库,来编译模板 
			
			//***Key Point 3: 从当前页面加载模板
			var template1=_.template($("#area1_template").html(),{hello:"Hello! You are welcome! "});
			//加载模板到对应的el属性中
			$("#area1").html(template1);

			//从外部文件加载模板
			//var template2=_.template($("#area2_template").html(),{footer:"Footer text~~~~"}); 
			//$("#area2").html(template2);
		},

		//* 事件绑定
		events: {
			//***Key Point 2: 绑定Dom中id为check的元素
			//Purpose:事件对应到代码处理,更新model数据, 从而联系到Key point 1
			"click #check": "checkIn",
		},
		
        //* 业务处理 (处理Model数据)
		checkIn: function () {
			var world_name = prompt("请问,您是哪星人?");
			if(world_name == "")
				world_name = '未知';

			var world = new World({ name: world_name });
			this.worlds.add(world);
		},

		//* View更新
		addOneWorld: function(model) {
			$("#world-list").append("<li>这里是来自<b>" + model.get('name') + "</b>星球的问候:hello world!</li>");
		}
	});
	//实例化AppView
	var appview = new AppView();

	// 3. 定义MVC中的Controller部分 *****
	var AppRouter=Backbone.Router.extend({
		routes:{
			'posts/:id' : 'getPost',  //对应的链接为<a href="#/posts/120">Post 120</a>
		    'download/*path':'downloadFile',//对应的链接为<a href="#/download/user/images/hey.gif">download gif</a>
		    ':route/:action':'loadView', //对应的链接为<a href="#/dashboard/graph">Load Route/Action View</a>
		    '*actions' : 'defaultRoute'
		},


		getPost : function(id){
			console.log('id=' + id);
			alert(id);
		},
		
		downloadFile : function(path){
			alert(path);	// user/images/hey.gif
		},

		loadView : function(route,action){
			alert(route+"_"+action);	// dashboard_graph
		},
		
		defaultRoute : function(actions){
		    alert("Default " + actions);
		}
	});
	//实例化AppRouter
	var app_router=new AppRouter;
	Backbone.history.start();
})(jQuery);
</script>
</html>

 

 

参考:

Backbone: http://backbonejs.org/

                  http://www.csser.com/tools/backbone/backbone.js.html(中文文档)

Backbone唯一的强依赖库参考 http://underscorejs.org/

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值