backbone初次使用及hello world
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 Item
s. 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 this. methodNames 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的更多相关文章
- backBone.js初识
一.单页面应用 1.单页面应用(single-page application :SPA),是指在浏览器中运行的应用,在使用期间不会重新加载页面. 2.它所有的活动局限于一个Web页面,仅在初始化加载 ...
- Backbone源码解析(六):观察者模式应用
卤煮在大概一年前写过backbone的源码分析,里面讲的是对一些backbone框架的方法的讲解.这几天重新看了几遍backbone的源码,才发现之前对于它的理解不够深入,只关注了它的一些部分的细节和 ...
- 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 的目的是 ...
- 使用backbone的history管理SPA应用的url
本文介绍如何使用backbone的history模块实现SPA应用里面的URL管理.SPA应用的核心在于使用无刷新的方式更改url,从而引发页面内容的改变.从实现上来看,url的管理和页面内容的管理是 ...
- Backbone中的model和collection在做save或者create操作时, 如何选择用POST还是PUT方法 ?
Model和Collection和后台的WEB server进行数据同步非常方便, 都只需要在实行里面添加一url就可以了,backbone会在model进行save或者collection进行cre ...
- Backbone.js 中的Model被Destroy后,不能触发success的一个原因
下面这段代码中, 当调用destroy时,backbone会通过model中的url,向服务端发起一个HTTP DELETE请求, 以删除后台数据库中的user数据. 成功后,会回调触发绑定到dest ...
- Backbone.js应用基础
前言: Backbone.js是一款JavaScript MVC应用框架,强制依赖于一个实用型js库underscore.js,非强制依赖于jquery:其主要组件有模型,视图,集合,路由:与后台的交 ...
- Backbone事件模块及其用法
事件模块Backbone.Events在Backbone中占有十分重要的位置,其他模块Model,Collection,View所有事件模块都依赖它.通过继承Events的方法来实现事件的管理,可以说 ...
- HashTable初次体验
用惯了数组.ArryList,初次接触到HashTable.Dictionary这种字典储存对于我来说简直就是高大上. 1.到底什么是HashTable HashTable就是哈希表,和数组一样,是一 ...
随机推荐
- SystemTap----常用变量、宏、函数和技巧
http://blog.csdn.net/moonvs2010/article/category/1570309
- MapReduce分析明星微博数据
互联网时代的到来,使得名人的形象变得更加鲜活,也拉近了明星和粉丝之间的距离.歌星.影星.体育明星.作家等名人通过互联网能够轻易实现和粉丝的互动,赚钱也变得前所未有的简单.同时,互联网的飞速发展本身也造 ...
- noi1816 画家问题(技巧搜索Dfs)
/* Problem 画家问题 假设一个ans数组存的是对每一个点的操作 0表示不图 1表示图 那么 对于原图 g 操作第三行时对第一行没有影响 同样往下类似的 所以 假设我们知道了ans的第一行就是 ...
- 单元测试--------Assert
名称 说明 AreEqual(Object, Object) 验证指定的两个对象是否相等. 如果两个对象不相等,则断言失败. AreEqual(Double, Double, Double) 验证 ...
- apache commons io包基本功能
1. http://jackyrong.iteye.com/blog/2153812 2. http://www.javacodegeeks.com/2014/10/apache-commons-io ...
- Java 6 Thread States and Life Cycle.
Ref: Java 6 Thread States and Life Cycle This is an example of UML protocol state machine diagram sh ...
- clientX 属性.
Syntax: event.clientX The clientX event attribute returns the horizontal coordinate (according to th ...
- oracle 查看用户表数目,表大小,视图数目等
查看当前用户的缺省表空间 SQL>select username,default_tablespace from user_users; 查看当前用户的角色 SQL>select * fr ...
- SQLSERVER 触发器 将一个服务器上的数据库中数据插入到另一个服务器上的数据库中怎么做
首先要执行 sp_addlinkedserver '服务器ip' 然后开始写语句 insert into ip.库名字.dbo.table select * from iserted
- inno setup 多语言安装
之前的安装程序默认语言为英文,现在我们需要将它变成中文,由于InnoSetup安装包中默认没有带中文语言文件,我们需要下载一个先: 到http://www.400gb.com/u/758954/123 ...