初探

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 元素。该属性可以是由 tagNameclassName 和 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入门的更多相关文章

  1. Web API 入门指南 - 闲话安全

    Web API入门指南有些朋友回复问了些安全方面的问题,安全方面可以写的东西实在太多了,这里尽量围绕着Web API的安全性来展开,介绍一些安全的基本概念,常见安全隐患.相关的防御技巧以及Web AP ...

  2. 转载-Web API 入门

    An Introduction to ASP.NET Web API 目前感觉最好的Web API入门教程 HTTP状态码 Web API 强势入门指南 Install Mongodb Getting ...

  3. Hadoop MapReduce编程 API入门系列之压缩和计数器(三十)

    不多说,直接上代码. Hadoop MapReduce编程 API入门系列之小文件合并(二十九) 生成的结果,作为输入源. 代码 package zhouls.bigdata.myMapReduce. ...

  4. Web API入门指南(安全)转

    安全检测的工具站点:https://www.owasp.org/index.php/Category:Vulnerability_Scanning_Tools Web API入门指南有些朋友回复问了些 ...

  5. 【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入门 ...

  6. Web API 入门指南

    Web API 入门指南 - 闲话安全2013-09-21 18:56 by 微软互联网开发支持, 231 阅读, 3 评论, 收藏, 编辑 Web API入门指南有些朋友回复问了些安全方面的问题,安 ...

  7. 使用Jax-rs 开发RESTfull API 入门

    使用Jax-rs 开发RESTfull API 入门 本文使用 Jersey 2开发RESTfull API.Jersey 2 是 JAX-RS 接口的参考实现 使用到的工具 Eclipse Neon ...

  8. Web API 入门 二 媒体类型

    还是拿上面 那篇 Web API 入门 一  的那个来讲 在product类中加一个时间属性

  9. HBase编程 API入门系列之create(管理端而言)(8)

    大家,若是看过我前期的这篇博客的话,则 HBase编程 API入门系列之put(客户端而言)(1) 就知道,在这篇博文里,我是在HBase Shell里创建HBase表的. 这里,我带领大家,学习更高 ...

随机推荐

  1. Javascript计算密码的强度

    用Javascript评估用户输入密码的强度 1.如果密码少于5位,那么就认为这是一个弱密码.2.如果密码只由数字.小写字母.大写字母或其它特殊符号当中的一种组成,则认为这是一个弱密码.3.如果密码由 ...

  2. Tr A(HDU 1575 快速矩阵幂模板)

    Tr A Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submis ...

  3. Java并发编程--多线程中的join方法详解

    Java Thread中, join()方法主要是让调用该方法的thread在完成run方法里面的部分后, 再执行join()方法后面的代码 例如:定义一个People类,run方法是输出姓名年龄. ...

  4. Robot FrameWork 教程链接

    1.  Robot Framework 教程: http://cgmblog.sinaapp.com/html/category/robot-framework 2.  Robot Framework ...

  5. iOS开发 自定义navigationleftItem 之后手势失效的问题

    @property (nonatomic, strong) UIViewController *currentShowVC; //设置代理 self.navigationController.inte ...

  6. Swift中数组集合-b

    数组(Array)是一串有序的由相同类型元素构成的集合.数组中的集合元素是有序的,可以重复出现. 声明一个Array类型的时候可以使用下面的语句之一. var studentList1:Array&l ...

  7. MySql 学习笔记 (派生表)

    派生表也是一种子查询那么它出现在 select * from ( select * from b <--这个就是派生表啦 )派生表其实不是个好东西,在生产的时候他是可以通过索引来过滤的,但是一但 ...

  8. hdu 1301 Jungle Roads

    http://acm.hdu.edu.cn/showproblem.php?pid=1301 #include <cstdio> #include <cstring> #inc ...

  9. redis 验证消息队列也是写磁盘的

    # 下面的例子将会进行把数据写入磁盘的操作: # 900秒(15分钟)之后,且至少1次变更 # 300秒(5分钟)之后,且至少10次变更 # 60秒之后,且至少10000次变更 # # 注意:你要想不 ...

  10. hdu5017:补题系列之西安网络赛1011

    补题系列之西安网络赛1011 题目大意:给定一个椭球: 求它到原点的最短距离. 思路: 对于一个椭球的标准方程 x^2/a^2 + y^2/b^2 +z^2/c^2=1 来说,它到原点的最短距离即为m ...