官网:http://backbonejs.org/

Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions,views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.

简而言之,Backbone.js是一个可以在前端组织MVC的javascript框架。

写的Javascript代码一旦多起来,没有一个好的组织,那就会像噩梦一样。

Backbone提供了Models, Collections, Views。Models 用来创建数据,校验数据,绑定事件,存储数据到服务器端;Collections 包含你创建的 functions;Views 用来展示数据。如此这般,在前端也做到了数据和显示分离。

Backbone依赖于Underscore.js,这是一个有很多常用函数的js文件(很好用).

与backbone.js类似的还有AngularJS,同样为js的mvc框架,两者对比:http://www.zhihu.com/question/21170137

backbone应用场景:http://www.zhihu.com/question/19720745

Backbone's only hard dependency is Underscore.js ( >= 1.5.0). For RESTful persistence, history support via Backbone.Router and DOM manipulation with Backbone.View, include jQuery, and json2.js for older Internet Explorer support. (Mimics of the Underscore and jQuery APIs, such as Lo-Dash and Zepto, will also tend to work, with varying degrees of compatibility.)

helloworld教程:http://arturadib.com/hello-backbonejs/

html模板:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>hello-backbonejs</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.0/backbone-min.js"></script> <script src="1.js"></script>
</body>
</html>

example1:This example illustrates the declaration and instantiation of a minimalist View

(function($){
// **ListView class**: Our main app view.
var ListView = Backbone.View.extend({
el: $('body'), // attaches `this.el` to an existing element.
// `initialize()`: Automatically called upon instantiation. Where you make all types of bindings, _excluding_ UI events, such as clicks, etc.
initialize: function(){
_.bindAll(this, 'render'); // fixes loss of context for 'this' within methods this.render(); // not all views are self-rendering. This one is.
},
// `render()`: Function in charge of rendering the entire view in `this.el`. Needs to be manually called by the user.
render: function(){
$(this.el).append("<ul> <li>hello world</li> </ul>");
}
}); // **listView instance**: Instantiate main app view.
var listView = new ListView();
})(jQuery);

This example illustrates the binding of DOM events to View methods.

Working example: 2.html.

//
(function($){
var ListView = Backbone.View.extend({
el: $('body'), // el attaches to existing element
// `events`: Where DOM events are bound to View methods. Backbone doesn't have a separate controller to handle such bindings; it all happens in a View.
events: {
'click button#add': 'addItem'
},
initialize: function(){
_.bindAll(this, 'render', 'addItem'); // every function that uses 'this' as the current object should be in here this.counter = 0; // total number of items added thus far
this.render();
},
// `render()` now introduces a button to add a new list item.
render: function(){
$(this.el).append("<button id='add'>Add list item</button>");
$(this.el).append("<ul></ul>");
},
// `addItem()`: Custom function called via `click` event above.
addItem: function(){
this.counter++;
$('ul', this.el).append("<li>hello world"+this.counter+"</li>");
}
}); var listView = new ListView();
})(jQuery);

events: Where DOM events are bound to View methods. Backbone doesn't have a separate controller to handle such bindings; it all happens in a View.

 (function($){
// **Item class**: The atomic part of our Model. A model is basically a Javascript object, i.e. key-value pairs, with some helper functions to handle event triggering, persistence, etc.
var Item = Backbone.Model.extend({
defaults: {
part1: 'hellosdf',
part2: 'worlsdfd'
}
}); // **List class**: A collection of `Item`s. Basically an array of Model objects with some helper functions.
var List = Backbone.Collection.extend({
model: Item
}); var ListView = Backbone.View.extend({
el: $('body'),
events: {
'click button#add': 'addItem'
},
// `initialize()` now instantiates a Collection, and binds its `add` event to own method `appendItem`. (Recall that Backbone doesn't offer a separate Controller for bindings...).
initialize: function(){
_.bindAll(this, 'render', 'addItem', 'appendItem'); // remember: every function that uses 'this' as the current object should be in here this.collection = new List();
this.collection.bind('add', this.appendItem); // collection event binder this.counter = 0;
this.render();
},
render: function(){
// Save reference to `this` so it can be accessed from within the scope of the callback below
var self = this;
$(this.el).append("<button id='add'>Add list item</button>");
$(this.el).append("<ul></ul>");
_(this.collection.models).each(function(item){ // in case collection is not empty
self.appendItem(item);
}, this);
},
// `addItem()` now deals solely with models/collections. View updates are delegated to the `add` event listener `appendItem()` below.
addItem: function(){
this.counter++;
var item = new Item();
item.set({
part2: item.get('part2') + this.counter // modify item defaults
});
this.collection.add(item); // add item to collection; view is updated via event 'add'
},
// `appendItem()` is triggered by the collection event `add`, and handles the visual update.
appendItem: function(item){
$('ul', this.el).append("<li>"+item.get('part1')+" "+item.get('part2')+"</li>");
}
}); var listView = new ListView();
})(jQuery);

Item class: The atomic part of our Model. A model is basically a Javascript object, i.e. key-value pairs, with some helper functions to handle event triggering, persistence, etc.

List class: A collection of Items. Basically an array of Model objects with some helper functions.

underscore bindAll:

bindAll_.bindAll(object, *methodNames) 
Binds a number of methods on the object, specified by methodNames, to be run in the context of that object whenever they are invoked. Very handy for binding functions that are going to be used as event handlers, which would otherwise be invoked with a fairly useless thismethodNames are required.

var buttonView = {
label : 'underscore',
onClick: function(){ alert('clicked: ' + this.label); },
onHover: function(){ console.log('hovering: ' + this.label); }
};
_.bindAll(buttonView, 'onClick', 'onHover');
// When the button is clicked, this.label will have the correct value.
jQuery('#underscore_button').bind('click', buttonView.onClick);

demo4:This example illustrates how to delegate the rendering of a Model to a dedicated View.

backbone初次使用及hello world的更多相关文章

  1. backBone.js初识

    一.单页面应用 1.单页面应用(single-page application :SPA),是指在浏览器中运行的应用,在使用期间不会重新加载页面. 2.它所有的活动局限于一个Web页面,仅在初始化加载 ...

  2. Backbone源码解析(六):观察者模式应用

    卤煮在大概一年前写过backbone的源码分析,里面讲的是对一些backbone框架的方法的讲解.这几天重新看了几遍backbone的源码,才发现之前对于它的理解不够深入,只关注了它的一些部分的细节和 ...

  3. MVC、MVP、MVVM、Angular.js、Knockout.js、Backbone.js、React.js、Ember.js、Avalon.js、Vue.js 概念摘录

    注:文章内容都是摘录性文字,自己阅读的一些笔记,方便日后查看. MVC MVC(Model-View-Controller),M 是指业务模型,V 是指用户界面,C 则是控制器,使用 MVC 的目的是 ...

  4. 使用backbone的history管理SPA应用的url

    本文介绍如何使用backbone的history模块实现SPA应用里面的URL管理.SPA应用的核心在于使用无刷新的方式更改url,从而引发页面内容的改变.从实现上来看,url的管理和页面内容的管理是 ...

  5. Backbone中的model和collection在做save或者create操作时, 如何选择用POST还是PUT方法 ?

    Model和Collection和后台的WEB server进行数据同步非常方便, 都只需要在实行里面添加一url就可以了,backbone会在model进行save或者collection进行cre ...

  6. Backbone.js 中的Model被Destroy后,不能触发success的一个原因

    下面这段代码中, 当调用destroy时,backbone会通过model中的url,向服务端发起一个HTTP DELETE请求, 以删除后台数据库中的user数据. 成功后,会回调触发绑定到dest ...

  7. Backbone.js应用基础

    前言: Backbone.js是一款JavaScript MVC应用框架,强制依赖于一个实用型js库underscore.js,非强制依赖于jquery:其主要组件有模型,视图,集合,路由:与后台的交 ...

  8. Backbone事件模块及其用法

    事件模块Backbone.Events在Backbone中占有十分重要的位置,其他模块Model,Collection,View所有事件模块都依赖它.通过继承Events的方法来实现事件的管理,可以说 ...

  9. HashTable初次体验

    用惯了数组.ArryList,初次接触到HashTable.Dictionary这种字典储存对于我来说简直就是高大上. 1.到底什么是HashTable HashTable就是哈希表,和数组一样,是一 ...

随机推荐

  1. 使用php glob函数查找文件,遍历文件目录(转)

    函数说明:array glob ( string $pattern [, int $flags ] )功能:寻找与模式匹配的文件路径,返回包含匹配文件(目录)的数组(注:被检查的文件必须是服务器系统的 ...

  2. swift 关于delegate

    Cocoa 开发中接口-委托 (protocol-delegate) 模式是一种常用的设计模式,它贯穿于整个 Cocoa 框架中,为代码之间的关系清理和解耦合做出了不可磨灭的贡献. 在 ARC 中,对 ...

  3. CentOS 通过yum来升级php到php5.6,yum upgrade php 没有更新包怎么办?

    在文章中,我们将展示在centOS系统下如何将php升级到5.6,之前通过yum来安装lamp环境,直接升级的话,提示没有更新包,也就是说默认情况下php5.3.3是最新 1.查看已经安装的php版本 ...

  4. 第六篇:python高级之网络编程

    python高级之网络编程   python高级之网络编程 本节内容 网络通信概念 socket编程 socket模块一些方法 聊天socket实现 远程执行命令及上传文件 socketserver及 ...

  5. int? 参数是这个的时候 是可以传入null的 而int的就不行

    such as     pager.CurrentPageIndex = (page != null ? (int)page : 1);

  6. E/Trace: error opening trace file: No such file or directory

    E/Trace: error opening trace file: No such file or directory (2) 有这一个错误,想了一下,然后发现是 AdroidManifest.xm ...

  7. maven项目下tomcat直接启动不了(LifecycleException)。报错如下截图

    经查,tomcat项目下的lib中没有jar包,发布的时候没有将jar包发布上去.这个问题在我的博客中以前遇到过.如何将maven的jar发布到项目中,我的博客里面有记载

  8. 使用SQL Server 2008远程链接时SQL数据库不成功的解决方法

    关键设置: 第一步(SQL2005.SQL2008): 开始-->程序-->Microsoft SQL Server 2008(或2005)-->配置工具-->SQL Serv ...

  9. JS判断浏览器是否支持某一个CSS3属性的方法

    var div = document.createElement('div'); console.log(div.style.transition); //如果支持的话, 会输出 "&quo ...

  10. APP被Rejected 的各种原因翻译(转)

    原文:http://www.cnblogs.com/sell/archive/2013/02/16/2913341.html Terms and conditions(法律与条款) 1.1 As a ...