(一)backbone - API入门
初探
backbone采用MVC模式,本身提供了模型、控制器和视图从而我们应用程序的骨架便形成。
Backbone.js 唯一重度依赖 Underscore.js. 对于 RESTful , history 的支持依赖于 Backbone.Router , DOM 处理依赖于Backbone.View , json2.js, 和 jQuery ( > 1.7) 或 Zepto 之一.
中文文档
http://www.css88.com/doc/backbone/
英文文档
http://documentcloud.github.io/backbone/
适用场景
充斥着大量Ajax交互的富应用页面,类应用程序和单页界面,数据操作和展示全部由客户端完成。
初略理解
Backbone的执行顺序:
路由(Backbone.Router)-> 模型(Backbone.Model)-> 视图(Backbone.View)
- 路由告诉你要去哪
App.Controllers.Routes = Backbone.Router.extend({
routes: {
"!/hello" : "hello",//使用#!/hello驱动路由 这里会去执行下面hello这个函数
},
hello : function(){
//新建一个模型,模型向后端请求更新内容成功后根据模型渲染新页面
var helloModel = new App.Models.Hello; //调用模板
helloModel.fetch({
success: function(model){ //成功拿到数据,调用视图渲染页面
var helloView = new App.Views.Hello({model: model});
helloView.trigger('change'); //绑定change事件
}
});
}
}); - 模型告诉该干些什么。这里是去拿数据,set是提供一个设置初始数据
App.Models.Hello = Backbone.Model.extend({
url: function() {
return '/index/test'; // 获得数据的后台接口地址。
},
initialize: function() {
this.set({'message':'hello world'}); // 前端定义一个message字段,name字段由接口提供。
}
}); - View展示有了什么
App.Views.Hello = Backbone.View.extend({
el: "body", //在哪里显示
template: $("#hello-container-template").html(), //获取模板 模板是用Mustache
initialize: function(options){
this.options = options;
this.bind('change', this.render);
this.model = this.options.model;
},
render: function(){ // render方法,目标只有两个:填充this.el,返回this以便链式操作。
$(this.el).html(Mustache.to_html(this.template,this.model.toJSON()));
return this;
}
}); - 最后,由一个全局类进行组装
var App = {
Models: {},
Views: {},
Controllers: {},
Collections: {},
initialize: function() {
new App.Controllers.Routes();
Backbone.history.start() // 要驱动所有的Backbone程序,Backbone.history.start()是必须的。
}
};
// 调用
App.initialize();
详解
•模型属性
定义模型、实例化
var User = Backbone.Model.extend({
initialize: function (name) {
this.set({name: name});
}
});
var user = new User('啦啦啦'); // 实例化
// 属性
user.set({ age: 999 });
user.get('age'); //
user.attributes;//{name: '啦啦啦',age:999}
user.arributes是一个对象字面量,我们不会直接操作他,因为我们使用get/set方法可以进行我们的验证流程。
使用validate方法来校验一个实例属性,默认情况没有任何验证:
var User = Backbone.Model.extend({
validate: function (attr) {
if (!attr.name || attr.name.length < 3) {
return 'too short';
}
if(!attr.age || !(/^\d{1,3}$/).test(attr.age)){
return 'ghost?';
}
}
});
// 不合法可以返回错误字符串或者Error对象,校验失败get/set方法就会触发error事件:
//统一的错误处理
user.bind('error', function (model, error) {
});
//给特定集合添加一个错误处理程序
user.set({ age: 999}, { error: function (model, error) { } });
•视图
backbone的视图并不是模板,而是一些控制类,视图代表一个UI逻辑块,负责一个简单的DOM内容
一个视图提供一个由 el 属性定义的 HTML 元素。该属性可以是由 tagName、className 和 id 属性相组合而构成的,或者是通过其本身的 el 值形成的
App.Views.Team = Backbone.View.extend({
initialize : function() {
_.bindAll(this, 'render', 'close'); // bindAll保证了所有给定的函数总是在指定的上下文中被调用
this.model.bind("change", this.render, this); // Render() 方法绑定到模型变更事件
this.model.bind('delete', this.remove); // 模型销毁需要视图绑定delete事件
}
className : '.team-element',
tagName : 'div',
model : new App.Models.Team
template: _.template($('#tmpt').html()), // 模板
render: function () {
$(this.el).html(this.template(this.model.toJSON()));
return this;
},
close: function () { },
remove: function () { $(this.el).remove() },
// 事件属性
events: {
'change input[type=checkbox]': 'toggleDone',
'click .destroy': 'clear'
},
toggoleDone: function () { },
clear; function () {}
});
•路由
控制器是一些路由和函数组成,当导航到这些路由时那些函数便调用
App.Routers.Main = Backbone.Router.extend({
// Hash maps for routes
routes : {
"" : "index",
"/teams" : "getTeams",
"/teams/:country" : "getTeamsCountry",
"/teams/:country/:name : "getTeam"
"*error" : "fourOfour"
},
// http://www.example.com 触发
index: function(){
// Homepage
},
// http://www.example.com/#/teams 触发
getTeams: function() {
// List all teams
},
// http://www.example.com/#/teams/country1 触发 getTeamsCountry() 传递 country1 作为参数
getTeamsCountry: function(country) {
// Get list of teams for specific country
},
// http://www.example.com/#/teams/country1/team1 触发 getTeamCountry() 传递 country1 和 team1 作为参数
getTeam: function(country, name) {
// Get the teams for a specific country and with a specific name
},
// http://www.example.com/#/something 触发 fourOfour() 以作 * (星号)使用。
fourOfour: function(error) {
// 404 page
}
});
// 要启动 Backbone,先实例化页面加载的路由器,并通过指令 Backbone.history.start() 方法监视散列片段中的任何变更
$(function(){
var router = new App.Routers.Main();
Backbone.history.start({pushState : true});
})
•与服务器同步
模型发生变化(保存),backbone就会使用ajax与服务器通讯(Backbone.sync),成功便更新客户端模型。
定义url,并且在服务器端处理rest形式请求,backbone会处理:
var User = Backbone.Model.extend({
url: '/users'
});
增删改查:
create => post /collection
read => get /collection[/id]
update => put /collection/id
delete => delete /collection/id //例如,我们要创建一个User实例,backbone会发送一个post请求道/uesrs,更新一个user实例,会发送至/users/id节点
使用save(attr, option)函数将模型保存至服务器,可以随意传递一个由属性和请求项组成的hash对象,若是模型有id,假设该模型在服务器上以存在,存在就是put请求,不然就post请求添加数据
var user = new User();
user.set({ name: '叶小钗' });
user.save(null, {
success: function () {
//保存成功
}
});
// 所有save都是异步的,通过success或者failure来监听ajax回调,我们一般与jquery合用了。
•自定义行为
在backbone视图读取或者保存模型到服务器时都会调用backbone.sync方法,
覆盖该方法来改变其默认行为(存入xml、本地存储):
//所有待完成的项都保存至本地存储命名空间“todos”中
Toto.prototype.localStorage = new Store('todos');
//重写backbone.sync
Backbone.sync = function (method, model, options) {
var resp, store = model.localStorage || model.collection.localStorage;
switch (method) {
case 'read': resp = model.id ? store.find(model) : store.findAll(); break;
case 'create': resp = store.create(model); break;
case 'update': resp = store.update(model); break;
case 'delete': resp = store.destroy(model); break;
}
if (resp) {
options.success(resp);
} else {
options.error('not find');
}
}
// 注: 每个模型或者集合只能覆盖各自的sync函数
扩展阅读
7条建议
http://ourjs.com/detail/5353191719fe673f1700000e
(一)backbone - API入门的更多相关文章
- Web API 入门指南 - 闲话安全
Web API入门指南有些朋友回复问了些安全方面的问题,安全方面可以写的东西实在太多了,这里尽量围绕着Web API的安全性来展开,介绍一些安全的基本概念,常见安全隐患.相关的防御技巧以及Web AP ...
- 转载-Web API 入门
An Introduction to ASP.NET Web API 目前感觉最好的Web API入门教程 HTTP状态码 Web API 强势入门指南 Install Mongodb Getting ...
- Hadoop MapReduce编程 API入门系列之压缩和计数器(三十)
不多说,直接上代码. Hadoop MapReduce编程 API入门系列之小文件合并(二十九) 生成的结果,作为输入源. 代码 package zhouls.bigdata.myMapReduce. ...
- Web API入门指南(安全)转
安全检测的工具站点:https://www.owasp.org/index.php/Category:Vulnerability_Scanning_Tools Web API入门指南有些朋友回复问了些 ...
- 【ASP.NET Web API教程】1 ASP.NET Web API入门
原文 [ASP.NET Web API教程]1 ASP.NET Web API入门 Getting Started with ASP.NET Web API第1章 ASP.NET Web API入门 ...
- Web API 入门指南
Web API 入门指南 - 闲话安全2013-09-21 18:56 by 微软互联网开发支持, 231 阅读, 3 评论, 收藏, 编辑 Web API入门指南有些朋友回复问了些安全方面的问题,安 ...
- 使用Jax-rs 开发RESTfull API 入门
使用Jax-rs 开发RESTfull API 入门 本文使用 Jersey 2开发RESTfull API.Jersey 2 是 JAX-RS 接口的参考实现 使用到的工具 Eclipse Neon ...
- Web API 入门 二 媒体类型
还是拿上面 那篇 Web API 入门 一 的那个来讲 在product类中加一个时间属性
- HBase编程 API入门系列之create(管理端而言)(8)
大家,若是看过我前期的这篇博客的话,则 HBase编程 API入门系列之put(客户端而言)(1) 就知道,在这篇博文里,我是在HBase Shell里创建HBase表的. 这里,我带领大家,学习更高 ...
随机推荐
- 【干货】国外程序员整理的 C++ 资源大全【转】
来自 https://github.com/fffaraz/awesome-cpp A curated list of awesome C/C++ frameworks, libraries, res ...
- VNC配置连接远程服务器桌面-linux\windows
一.VNC配置连接远程服务器桌面 1.服务器安装VNC-server # yum -y install vnc-server 2.配置VNC连接登陆密码 # vncpasswd 回车 3.配置VNC- ...
- 记录使用Hibernate查询bean中字段和数据库列类型不匹配问题
今天在工程中遇到Hibernate查询的时候,bean中的字段和数据库中的字段不符合(bean中有pageTime字段,但是数据库中没有此列)报错问题. 具体问题环境: 在auto_off表中,off ...
- Express4+Mongodb极简入门实例
一.准备工作: 1.启动mongodb:bin目录下运行 2.在test数据库里插入一条数据: 二.正式开始: 1.通过应用生成器工具 express 快速创建一个应用的骨架,参考Express中文网 ...
- jquery serialize的使用
serialize() 方法通过序列化表单值,创建 URL 编码文本字符串. <!DOCTYPE html> <html lang="en"> <he ...
- Lazy Load Plugin for jQuery延迟加载测试成功
一直需要的功能,网页图片太多时对于降低网络流量超有用. 最新的V1.9.3版本其实已不用修改就可以起作用了. 不用网上说的要自己修改代码.
- 如何给开源的DUILib支持Accessibility(论述了DUILib的六个缺点,很精彩)
最近的工作是给开源的DUILib支持Accessibility, 一些经验记录并分享下. 微软的Accessibility其实Windows平台上一个挺重要的东西, 尽管在国内不受重视,但是如果你 ...
- Qt中文乱码问题(比较清楚,同一个二进制串被解释成不同的语言)
文章来源:http://blog.csdn.net/brave_heart_lxl/article/details/7186631 以下是dbzhang关于qt中文乱码问题原因的阐述,觉得不错: 首先 ...
- shell中的IFS详解
在bash中IFS是内部的域分隔符,manual中对其的叙述如下:IFS The Internal Field Separator that is used for word splitting af ...
- TestNG基本注解(注释)
传统的方式来表示JUnit3中的测试方法是测试自己的名字前缀.标记一个类中的某些方法,具有特殊的意义,这是一个非常有效的方法,但命名不很好的扩展(如果我们想添加更多标签为不同的框架?),而非缺乏灵活性 ...