backbone初次使用及hello world

时间:2022-05-02 06:03:11

官网: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&period;js初识

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

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

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

  3. MVC、MVP、MVVM、Angular&period;js、Knockout&period;js、Backbone&period;js、React&period;js、Ember&period;js、Avalon&period;js、Vue&period;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&period;js 中的Model被Destroy后,不能触发success的一个原因

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

  7. Backbone&period;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. 捕获当前事件作用的对象event&period;target和event&period;srcElement

    语法: //返回事件的目标节点(触发该事件的节点). event.target //FF,Chrome event.srcElement //IE 栗子: var oDiv=document.getE ...

  2. Java for LeetCode 160 Intersection of Two Linked Lists

    Write a program to find the node at which the intersection of two singly linked lists begins. For ex ...

  3. Fiddler 模拟post 提交

    在使用Fiddler 提交post表单的时候, 一定要加上以下code: Content-Type: application/x-www-form-urlencoded 意思为: 窗体数据被编码为名称 ...

  4. 卸载oracle 11g数据库

    完全卸载oracle11g步骤:1. 开始->设置->控制面板->管理工具->服务 停止所有Oracle服务.2. 开始->程序->oracle - OraHome ...

  5. python实战案例--银行系统

    stay hungry, stay foolish.求知若饥,虚心若愚. 今天和大家分享一个python的实战案例,很多人在学习过程中都希望通过一些案例来试一下,也给自己一点动力.那么下面介绍一下这次 ...

  6. Python数据结构之栈的实现

    一图胜千言,看图! 代码code: #coding:utf-8 #常见数据结构之栈的实现 class Stack(): #创建Stack类 def __init__(st,size): st.stac ...

  7. Leetcode刷题第004天

    class Solution { public: int findKthLargest(vector<int>& nums, int k) { , nums.size()-, k) ...

  8. python全栈开发 &ast; 27知识点汇总 &ast; 180710

    27   time  os  sys  模块 time 模块 一.表示时间的三种方式 时间戳(timestamp), 元组(struct_time),格式化时间字符串(Format string) 小 ...

  9. HTTP请求中POST与GET的区别

      本文章已收录于:   一.原理区别 一般我们在浏览器输入一个网址访问网站都是GET请求;再FORM表单中,可以通过设置Method指定提交方式为GET或者POST提交方式,默认为GET提交方式. ...

  10. TimeLine CSS&sol;Javascript 时间线

    https://casbootadminserver.herokuapp.com/#/applications/23bd8218/trace