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就是哈希表,和数组一样,是一 ...
随机推荐
- iOS View的Frame和bounds之区别,setbounds使用(深入探究)
前言: 在ios开发中经常遇到两个词Frame和bounds,本文主要阐述Frame和bound的区别,尤其是bound很绕,较难理解. 一.首先,看一下公认的资料: 先看到下面的代码你肯定就明白了一 ...
- Block之变量作用域
在使用block的过程中经常会调用不同类型.不同作用域的变量,如果对这些变量作用域的理解稍有偏差,就会出现问题.故此特意整理出block中会经常使用到的几种变量,如有补充,欢迎指出. 1. 局部变量 ...
- warning:This application is modifying the autolayout engine from a background thread
警告提示:This application is modifying the autolayout engine from a background thread, which can lead to ...
- 虚拟机如何访问tomcat
首先需要把tomcat和jdk整到虚拟机里,然后再在虚拟机里安装tomcat和jdk. 一.怎样把tomcat和jdk整到虚拟机里? 1,需要“ha_Serv-U6406 ftp服务器”的帮助,所以先 ...
- java的List接口的实现类 ArrayList,LinkedList,Vector 的区别
Java的List接口有3个实现类,分别是ArrayList.LinkedList.Vector,他们用于存放多个元素,维护元素的次序,而且允许元素重复. 3个具体实现类的区别如下: 1. Array ...
- U3D 内置对象
在U3D里面提供了一个Time对象: void OnGUI(){ Debug.Log("########################"); GUILayout.Label (& ...
- JS escape()、encodeURI()和encodeURIComponent()的区别
1.实例说明: var url='http://wx.jnqianle.com/content/images/冰皮月饼.jpg?name=张三丰&age=11'; console.info(w ...
- angularjs kindEditor 中content获得不到值
angularjs kindEditor 中content获得不到值 需要修改下angular-kindeditor.js angular-kindeditor.js if (KindEditor) ...
- angularjs 将带标签的内容解析后返回
参考地址:http://okashii.lofter.com/post/1cba87e8_29e0fab 引入angular-sanitize.js文件 注入ngSanitize 页面数据绑定 ng- ...
- solve_lock-1024-大功告成
create or replace procedure solve_lock_061203(v_msg out varchar2) as v_sql varchar2(3000); --定义 v_s ...