官网: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. BINARY and varBINARY

    BINARY(n) ,varBINARY(n): N代表字节数 utf8: mysql> CREATE TABLE t (c BINARY()); Query OK, rows affected ...

  2. QSplashScreen类实现Qt程序启动画面

      QSplashScreen类实现Qt程序启动画面 收藏人:zwsj     2013-09-13 | 阅:569  转:6    |   来源   |  分享               程序启动 ...

  3. php mysqli注意问题

    今天写了这个一段代码 function ip_get_method($action , $device){ if($action != 'search'){ request_die(false,'un ...

  4. mac tips

    1. Mac Terminal color for different types 在 ~ 先建立一个文件  ~/.bash_profile 加入下面的两行:export CLICOLOR=1expo ...

  5. react初识

    如下是在研究中记录的笔记: 1,作用:局部的更新dom结构;虚拟dom保证性能2,和mvc不同,mvc是对于技术上的分离(分类),而react是组件上的分离,每个视图模块分离,复用,以视图模块为单位3 ...

  6. 重载,重写和super

    1.重载的概念:----->在同一个类中,允许存在同名函数,但它们的参数个数或者参数类型不同即可.public static void main(String[] args){System.ou ...

  7. Spring中@Autowired注解与自动装配

    1 使用配置文件的方法来完成自动装配我们编写spring 框架的代码时候.一直遵循是这样一个规则:所有在spring中注入的bean 都建议定义成私有的域变量.并且要配套写上 get 和 set方法. ...

  8. C++中new的用法

    new int;//开辟一个存放整数的存储空间,返回一个指向该存储空间的地址(即指针) new int(100);//开辟一个存放整数的空间,并指定该整数的初值为100,返回一个指向该存储空间的地址 ...

  9. ExtJS4 动态加载

    由于有人说不要每次都调用ext-all.js,会影响性能,所以有考虑动态加载,动态加载时页面调用ext.js(4.0.7在调试时可考虑用ext-dev.js),然后在onReady之前调用 Ext.L ...

  10. 从windows到Linux-ubuntu新手

    版本选择: 经多次实验,Ubuntu个人认为长期支持(LTS)版才值得装. VMware9中测试:Ubuntu10.04开机内存170M,Ubuntu12.04开机内存340M. 个人感觉Ubuntu ...