初探

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. Css 应用一

    Placeholder使用 CSS3里有相应的通用的对Placeholder提示信息美化的方法.你可以设置提示信息文字的颜色,透明度,背景色等. 为了最大化的兼容所有浏览器,给CSS里的placeho ...

  2. 有n人围成一圈,顺序排号。从第1个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来的第几号的那位。

    #include <iostream> using namespace std; int main() { int i,j,n,m,k,*p,num[100];k=m=0;   cin&g ...

  3. php魔术方法——属性重载方法

    php有一类很神奇的方法,这些方法是保留方法,通常不会在外部被显式调用,他们使用双下划线(__)开头,他们被称为魔术方法(Magic Methods).php官方也不建议定义其他双下划线开头的方法. ...

  4. [转]关于Chrome不能登录和同步的解决方法

    原帖地址:http://tieba.baidu.com/p/3086127792?pn=1 在本机的hosts文件(C:\Windows\System32\drivers\etc)里加入下面内容: # ...

  5. Regular expression cheat sheet

    \s white-space characters \S Non-white-space characters \d digital numbers \D non-digital numbers \w ...

  6. cf E. Dima and Magic Guitar

    http://codeforces.com/contest/366/problem/E |x1-x2|+|y1-y2|有四种情况 1.-(x1-x2)+(y1-y2); 2.(x1-x2)-(y1-y ...

  7. hdu Big Number

    #include <cstdio> #include <cstring> #include <cmath> using namespace std; int mai ...

  8. About Undefined Behavior[译文]

    原文:blog.llvm.org/2011/05/what-every-c-programmer-should-know.html 人们偶尔会问为什么LLVM的汇编代码有时会在优化器打开时产生SIGT ...

  9. 【转】 boot.img的解包与打包

    原文网址:http://blog.csdn.net/wh_19910525/article/details/8200372 Android 产品中,内核格式是Linux标准的zImage,根文件系统采 ...

  10. usaco5.5-Picture

    离散化计算重叠矩形的周长. 称平行于x轴的边为横边,我们以横边为例,某一矩形中y坐标比较小的横边我们称为始边,另一边我们称为终边.用一条扫描线从下往上扫描,当扫到一条始边的时候,如果这条始边的正下方出 ...