SlideShare a Scribd company logo
1 of 41
前端MVC之BACKBONE.JS
Single page app
 特点:

    页面不整体刷新


    与服务器的交互均由Ajax完成


    服务端只负责提供数据接口(瘦服务器)


    逻辑、展现、行为都交给javascript来处理(胖客户端)


    速度更快、体验较好
问题

   JS开发量较大、逻辑较复杂


   如果整个App只有一个URL,不便于收藏和传播


   无浏览器历史记录,浏览器前进后退按钮失效


   对搜索引擎不友好
前端MVC


   使程序结构清晰、便于理解

   减少重复劳动

   易于扩展
Backbone.js



Backbone.js通过Models、Collections、Views
使web应用程序具有良好的结构
使用Backbone的网站
Backbone.Model


  Model包含数据和与数据相关的逻辑。

     转换、验证、需计算的属性、访问控制等。
Javascript中一条Todo通常表示如下:
{
    text: ‚这是一条待做事项‛,
    done: false,
    order: 5
}
以Backbone来表示这条Todo:
 var Todo = Backbone.Model.extend({
     …
     toggle: function(){
         this.save({done: !this.get(‚done‛)});
     },
     initialize: function() {
        console.log(‚model已经创建‛);
     }
     …
 });

 var todoItem = new Todo({
     text: ‚这是一条待做事项‛,
     done: false,
     order: 5
 });
验证
var Todo = Backbone.Model.extend({
     defaults: {
        done: fase
     },
    validate: function(attrs) {
        if (attrs.text.length < 2) {
            return ‚待做事项的内容不得少于两个字‛;
        },
        …
    }
})
todo.get(‚title‛);

todo.set({title: ‚又一条todo‛, done: true});

todo.has(‚done‛);

todo.clear();

todo.fetch();

todo.save();
Backbone.Collection

   Collection就是Model的有序集合

      change事件,当所包含的Model发生变化时触发

      add、remove事件

      从服务器获取(fetch)数据
var TodoList = Backbone.Collection.extend({
      url    : './todos',
      model: Todo,
      done : function() {
        return this.filter(function(todo) { return
todo.get('done'); });
      },
      remaining: function() {
            return this.without.apply( this, this.done() );
      }
});
var list = new TodoList([
      {text: "aaa", done: false, order: 1},
      {text: "bbb", done: false, order: 2},
      {text: "ccc", done: false, order: 3},
      {text: "ddd", done: false, order: 4}
]);
list.add({text: ‚一条待做事项‛, done: false, order: 5});

list.reset({text: ‚待做事项‛, done: false, order: 7});

var todoItem = new Todo({ … });

list.add(todoItem);

list.toJSON();

list.get(id);

list.at(5);
list.fetch();


list.fetch({data: {page: 3}});


list.create()



var todoItem = new Todo({ … });
todoItem.save();
list.add(todoItem);
和服务器端的通信

   model.save()


   model.fetch()


   model.destroy()


   collection.fetch()


   collection.creat()
Backbone.sync

    RESTful架构
    http://www.ruanyifeng.com/blog/2011/09/restful.html


   每一个URI代表一种资源;


   客户端和服务器之间,传递这种资源的某种表现层;


   客户端通过四个HTTP动词,对服务器端资源进行操作,实现"表现层
    状态转化"。
/tasks (URL只含名词,不含动词)

 四个HTTP动词表示要对资源进行何种操作
 Create   POST   /tasks
 Read     GET    /tasks[/id]
 Update   PUT    /tasks/id
 Delete   DELETE /tasks/id
Backbone.Router


    Router为Web应用中的不同状态提供可链接的,可作为收藏的、可分享的URL;


    为客户端页面提供路由,并将它们与方法和事件关联起来。
HTML5之前,使用hash,如在URL末尾加#page
如:http://www.tttt.com/aaa#page


现在高级浏览器支持history.pushState,可以直接在后面加/page
如:http://www.tttt.com/aaa/page
var Workspace = Backbone.Router.extend({
 routes: {
      "help":                  "help",   // #help
      "search/:query":         "search", // #search/kiwis
      "search/:query/p:page": "search"   // #search/kiwis/p7
 },
 help: function() {
      ...
 },
 search: function(query, page) {
      //query = kiwis    page = 7
      ...
 }
});
var router = new Workspace();


router.on(‚route:search‛, function(query) {


});


router.navigate(‚search/kiwis‛);
router.navigate(‚search/kiwis‛, {trigger: true});
Backbone.history.start();

Backbone.history.start({
  pushState: true,
  root:‛/public/search‛
});
Backbone.View



 Backbone.View.extend(properties, [classProperties]);
实例化的时候需创建的View的根节点
var DocumentRow = Backbone.View.extend({
    tagName: "li‛,
    className: ‛todo-item‛,                          给视图内的元素绑定事件

    events: {
        "click .check"              : "toggleDone",
        "dblclick div.todo-text"    : "edit",
        "click span.todo-destroy"   : "clear",
        "keypress .todo-input"      : "updateOnEnter‛
    },
    render: function() {
        $(this.el).html(this.template(this.model.toJSON()));
    },                                      事件处理函数和其他方法
    toggleDone: {},
    edit: function() {},
    clear: function() {}
});
this.$(selector)           $(selector, this.el)

ui.Chapter = Backbone.View.extend({
  serialize : function() {
    return {
      title: this.$(".title").text(),
      start: this.$(".start-page").text(),
      end : this.$(".end-page").text()
    };
  }
});
var Bookmark = Backbone.View.extend({
 …
 render: function() {
      $(this.el).html(this.template(this.model.toJSON()));
      return this;
 }
 …
});
JS模版引擎


JS模版引擎简化了将数据转换成HTML串的过程已
     成为Web app不可或缺的一部分

     可减少重复劳动、节省开发和调试时间
Underscore.js template
{text: ‘这是一条待做事项’, done: false, order: 5}
<script id="item-template" type="text/template">
  <div class="todo <%= done ? 'done' : '' %>">
    <div class="display">
      <input class="check" type="checkbox" <%= done ?
'checked="checked"' : '' %> />
      <div class="todo-text"></div>
      <span id="todo-destroy"></span>
    </div>
    <div class="edit">
      <input type="text" value="" class="todo-input"/>
    </div>
  </div>
</script>
window.TodoView = Backbone.View.extend({
 tagName : "li‛,
 template: _.template( $('#item-template').html() ),
 render    : function() {
      $(this.el).html(this.template(this.model.toJSON()));
      this.setText();
      return this;
 }
});
Mustache.js
Mustache.to_html(template, data);

    https://github.com/janl/mustache.js/
EJS

template = new EJS({url: '/mytemplate.ejs'})


html = new EJS({url: '/template.ejs'}).render(data)


f = new EJS({url: '/mytemplate.ejs'}).update('my_element')


new EJS({url: '/mytemplate.ejs'}).update('my_element', '/data.json')


new EJS({url: '/mytemplate.ejs'}).update('my_element', {supplies:
['mop']})


http://embeddedjs.com/
http://code.google.com/p/embeddedjavascript/wiki/Templates
事件驱动

          事件引发Model的变化



       click submit enter change …

View                                   Model
            事件引发View的改变
                                     Collectio
                                     n
         change reset add remove
              sync destroy …
Controller


Controller是Model和View的中介,当Model变
化时负责更新View,当View发生变化时负责更新
Model
   Model        • Backbone.Model

   View         • Backbone.Collectio
                   n
   Controller
                 • Backbone.View

                 • Backbone.Router
Thank you!

More Related Content

What's hot

React vs Flux
React vs FluxReact vs Flux
React vs FluxLC2009
 
JQuery Mobile 框架介紹與使用 20140713
JQuery Mobile 框架介紹與使用 20140713JQuery Mobile 框架介紹與使用 20140713
JQuery Mobile 框架介紹與使用 20140713EZoApp
 
JQuery Mobile 框架介紹與使用
JQuery Mobile 框架介紹與使用JQuery Mobile 框架介紹與使用
JQuery Mobile 框架介紹與使用EZoApp
 
视图模式
视图模式视图模式
视图模式Li Zhang
 
Web设计 4 锋利的j_query(进入企业级应用阶段)
Web设计 4 锋利的j_query(进入企业级应用阶段)Web设计 4 锋利的j_query(进入企业级应用阶段)
Web设计 4 锋利的j_query(进入企业级应用阶段)ziggear
 
ASP.NET Core 2.1設計新思維與新發展
ASP.NET  Core 2.1設計新思維與新發展ASP.NET  Core 2.1設計新思維與新發展
ASP.NET Core 2.1設計新思維與新發展江華 奚
 
20131004 - Backbone js 介紹 by Bryan
20131004 - Backbone js  介紹 by Bryan20131004 - Backbone js  介紹 by Bryan
20131004 - Backbone js 介紹 by BryanLearningTech
 
Introduction to CodeIgniter
Introduction to CodeIgniterIntroduction to CodeIgniter
Introduction to CodeIgniterChun-Kai Wang
 
Template mb-kao
Template mb-kaoTemplate mb-kao
Template mb-kaoxwcoder
 
2021.laravelconf.tw.slides3
2021.laravelconf.tw.slides32021.laravelconf.tw.slides3
2021.laravelconf.tw.slides3LiviaLiaoFontech
 
Uliweb设计分享
Uliweb设计分享Uliweb设计分享
Uliweb设计分享modou li
 
Real World ASP.NET MVC
Real World ASP.NET MVCReal World ASP.NET MVC
Real World ASP.NET MVCjeffz
 
Backbone.js and MVW 101
Backbone.js and MVW 101Backbone.js and MVW 101
Backbone.js and MVW 101Jollen Chen
 
Backbone js and requirejs
Backbone js and requirejsBackbone js and requirejs
Backbone js and requirejsChi-wen Sun
 
Vic weekly learning_20160325
Vic weekly learning_20160325Vic weekly learning_20160325
Vic weekly learning_20160325LearningTech
 

What's hot (20)

React vs Flux
React vs FluxReact vs Flux
React vs Flux
 
jQuery Mobile
jQuery MobilejQuery Mobile
jQuery Mobile
 
JQuery Mobile 框架介紹與使用 20140713
JQuery Mobile 框架介紹與使用 20140713JQuery Mobile 框架介紹與使用 20140713
JQuery Mobile 框架介紹與使用 20140713
 
Vue.js
Vue.jsVue.js
Vue.js
 
JQuery Mobile 框架介紹與使用
JQuery Mobile 框架介紹與使用JQuery Mobile 框架介紹與使用
JQuery Mobile 框架介紹與使用
 
视图模式
视图模式视图模式
视图模式
 
I os 09
I os 09I os 09
I os 09
 
Web设计 4 锋利的j_query(进入企业级应用阶段)
Web设计 4 锋利的j_query(进入企业级应用阶段)Web设计 4 锋利的j_query(进入企业级应用阶段)
Web设计 4 锋利的j_query(进入企业级应用阶段)
 
How tovuejs
How tovuejsHow tovuejs
How tovuejs
 
ASP.NET Core 2.1設計新思維與新發展
ASP.NET  Core 2.1設計新思維與新發展ASP.NET  Core 2.1設計新思維與新發展
ASP.NET Core 2.1設計新思維與新發展
 
20131004 - Backbone js 介紹 by Bryan
20131004 - Backbone js  介紹 by Bryan20131004 - Backbone js  介紹 by Bryan
20131004 - Backbone js 介紹 by Bryan
 
Introduction to CodeIgniter
Introduction to CodeIgniterIntroduction to CodeIgniter
Introduction to CodeIgniter
 
Template mb-kao
Template mb-kaoTemplate mb-kao
Template mb-kao
 
2021.laravelconf.tw.slides3
2021.laravelconf.tw.slides32021.laravelconf.tw.slides3
2021.laravelconf.tw.slides3
 
Uliweb设计分享
Uliweb设计分享Uliweb设计分享
Uliweb设计分享
 
Real World ASP.NET MVC
Real World ASP.NET MVCReal World ASP.NET MVC
Real World ASP.NET MVC
 
J query
J queryJ query
J query
 
Backbone.js and MVW 101
Backbone.js and MVW 101Backbone.js and MVW 101
Backbone.js and MVW 101
 
Backbone js and requirejs
Backbone js and requirejsBackbone js and requirejs
Backbone js and requirejs
 
Vic weekly learning_20160325
Vic weekly learning_20160325Vic weekly learning_20160325
Vic weekly learning_20160325
 

Similar to 前端MVC之backbone

Spring 2.x 中文
Spring 2.x 中文Spring 2.x 中文
Spring 2.x 中文Guo Albert
 
JdonFramework中文
JdonFramework中文JdonFramework中文
JdonFramework中文banq jdon
 
旺铺前端设计和实现
旺铺前端设计和实现旺铺前端设计和实现
旺铺前端设计和实现hua qiu
 
HTML5概览
HTML5概览HTML5概览
HTML5概览Adam Lu
 
Struts+Spring+Hibernate整合教程
Struts+Spring+Hibernate整合教程Struts+Spring+Hibernate整合教程
Struts+Spring+Hibernate整合教程yiditushe
 
Struts+Spring+Hibernate整合教程
Struts+Spring+Hibernate整合教程Struts+Spring+Hibernate整合教程
Struts+Spring+Hibernate整合教程appollo0312
 
Script with engine
Script with engineScript with engine
Script with engineWebrebuild
 
ASP.NET Core MVC 2.2從開發到測試 - Development & Unit Testing
ASP.NET Core MVC 2.2從開發到測試 - Development & Unit TestingASP.NET Core MVC 2.2從開發到測試 - Development & Unit Testing
ASP.NET Core MVC 2.2從開發到測試 - Development & Unit Testing江華 奚
 
异步编程与浏览器执行模型
异步编程与浏览器执行模型异步编程与浏览器执行模型
异步编程与浏览器执行模型keelii
 
Asp.net mvc 培训
Asp.net mvc 培训Asp.net mvc 培训
Asp.net mvc 培训lotusprince
 
Underscore
UnderscoreUnderscore
Underscorecazhfe
 
Jquery指南
Jquery指南Jquery指南
Jquery指南yiditushe
 
網站設計100步
網站設計100步網站設計100步
網站設計100步evercislide
 
Java华为面试题
Java华为面试题Java华为面试题
Java华为面试题yiditushe
 
基于J2 Ee 的通用Web 信息系统框架设计与实现
基于J2 Ee 的通用Web 信息系统框架设计与实现基于J2 Ee 的通用Web 信息系统框架设计与实现
基于J2 Ee 的通用Web 信息系统框架设计与实现yiditushe
 
OPOA in Action -- 使用MagixJS简化WebAPP开发
OPOA in Action -- 使用MagixJS简化WebAPP开发OPOA in Action -- 使用MagixJS简化WebAPP开发
OPOA in Action -- 使用MagixJS简化WebAPP开发leneli
 
JQuery 学习
JQuery 学习JQuery 学习
JQuery 学习cssrain
 
從 Web Site 到 Web Application,從 Web Services 到 Mobile Services
從 Web Site 到 Web Application,從 Web Services 到 Mobile Services從 Web Site 到 Web Application,從 Web Services 到 Mobile Services
從 Web Site 到 Web Application,從 Web Services 到 Mobile ServicesKuo-Chun Su
 

Similar to 前端MVC之backbone (20)

Spring 2.x 中文
Spring 2.x 中文Spring 2.x 中文
Spring 2.x 中文
 
JdonFramework中文
JdonFramework中文JdonFramework中文
JdonFramework中文
 
旺铺前端设计和实现
旺铺前端设计和实现旺铺前端设计和实现
旺铺前端设计和实现
 
HTML5概览
HTML5概览HTML5概览
HTML5概览
 
Struts+Spring+Hibernate整合教程
Struts+Spring+Hibernate整合教程Struts+Spring+Hibernate整合教程
Struts+Spring+Hibernate整合教程
 
Struts+Spring+Hibernate整合教程
Struts+Spring+Hibernate整合教程Struts+Spring+Hibernate整合教程
Struts+Spring+Hibernate整合教程
 
Mvc
MvcMvc
Mvc
 
Script with engine
Script with engineScript with engine
Script with engine
 
ASP.NET Core MVC 2.2從開發到測試 - Development & Unit Testing
ASP.NET Core MVC 2.2從開發到測試 - Development & Unit TestingASP.NET Core MVC 2.2從開發到測試 - Development & Unit Testing
ASP.NET Core MVC 2.2從開發到測試 - Development & Unit Testing
 
异步编程与浏览器执行模型
异步编程与浏览器执行模型异步编程与浏览器执行模型
异步编程与浏览器执行模型
 
Asp.net mvc 培训
Asp.net mvc 培训Asp.net mvc 培训
Asp.net mvc 培训
 
react-zh-hant.pdf
react-zh-hant.pdfreact-zh-hant.pdf
react-zh-hant.pdf
 
Underscore
UnderscoreUnderscore
Underscore
 
Jquery指南
Jquery指南Jquery指南
Jquery指南
 
網站設計100步
網站設計100步網站設計100步
網站設計100步
 
Java华为面试题
Java华为面试题Java华为面试题
Java华为面试题
 
基于J2 Ee 的通用Web 信息系统框架设计与实现
基于J2 Ee 的通用Web 信息系统框架设计与实现基于J2 Ee 的通用Web 信息系统框架设计与实现
基于J2 Ee 的通用Web 信息系统框架设计与实现
 
OPOA in Action -- 使用MagixJS简化WebAPP开发
OPOA in Action -- 使用MagixJS简化WebAPP开发OPOA in Action -- 使用MagixJS简化WebAPP开发
OPOA in Action -- 使用MagixJS简化WebAPP开发
 
JQuery 学习
JQuery 学习JQuery 学习
JQuery 学习
 
從 Web Site 到 Web Application,從 Web Services 到 Mobile Services
從 Web Site 到 Web Application,從 Web Services 到 Mobile Services從 Web Site 到 Web Application,從 Web Services 到 Mobile Services
從 Web Site 到 Web Application,從 Web Services 到 Mobile Services
 

前端MVC之backbone