zoukankan      html  css  js  c++  java
  • 初入backbone

    英文的文档网址 http://backbonejs.org/

    中文的文档网址 http://www.css88.com/doc/backbone/     (网上有很多,可以自行挑选)

    我补充一下英文文档中有的但是中文文档中没有的一些东西。自己看看顺便翻译。也不知道对不对,就先翻着了。。如果有什么不对的地方欢迎指正~~


    Getting Started

    When working on a web application that involves a lot of JavaScript, one of the first things you learn is to stop tying your data to the DOM. It's all too easy to create JavaScript applications that end up as tangled piles of jQuery selectors and callbacks, all trying frantically to keep data in sync between the HTML UI, your JavaScript logic, and the database on your server. For rich client-side applications, a more structured approach is often helpful.

    With Backbone, you represent your data as Models, which can be created, validated, destroyed, and saved to the server. Whenever a UI action causes an attribute of a model to change, the model triggers a "change" event; all the Views that display the model's state can be notified of the change, so that they are able to respond accordingly, re-rendering themselves with the new information. In a finished Backbone app, you don't have to write the glue code that looks into the DOM to find an element with a specific id, and update the HTML manually — when the model changes, the views simply update themselves.

    Philosophically, Backbone is an attempt to discover the minimal set of data-structuring (models and collections) and user interface (views and URLs) primitives that are generally useful when building web applications with JavaScript. In an ecosystem where overarching, decides-everything-for-you frameworks are commonplace, and many libraries require your site to be reorganized to suit their look, feel, and default behavior — Backbone should continue to be a tool that gives you the freedom to design the full experience of your web application.

    If you're new here, and aren't yet quite sure what Backbone is for, start by browsing the list of Backbone-based projects.

    Models and Views

    Model-View Separation.

    The single most important thing that Backbone can help you with is keeping your business logic separate from your user interface. When the two are entangled, change is hard; when logic doesn't depend on UI, your interface becomes easier to work with.

    Model
    • Orchestrates data and business logic.
    • Loads and saves from the server.
    • Emits events when data changes.
    View
    • Listens for changes and renders UI.
    • Handles user input and interactivity.
    • Sends captured input to the model.

    Model manages an internal table of data attributes, and triggers "change" events when any of its data is modified. Models handle syncing data with a persistence layer — usually a REST API with a backing database. Design your models as the atomic reusable objects containing all of the helpful functions for manipulating their particular bit of data. Models should be able to be passed around throughout your app, and used anywhere that bit of data is needed.

    View is an atomic chunk of user interface. It often renders the data from a specific model, or number of models — but views can also be data-less chunks of UI that stand alone. Models should be generally unaware of views. Instead, views listen to the model"change" events, and react or re-render themselves appropriately.

    Collections

    Model Collections.

    Collection helps you deal with a group of related models, handling the loading and saving of new models to the server and providing helper functions for performing aggregations or computations against a list of models. Aside from their own events, collections also proxy through all of the events that occur to models within them, allowing you to listen in one place for any change that might happen to any model in the collection.

    API Integration

    Backbone is pre-configured to sync with a RESTful API. Simply create a new Collection with the url of your resource endpoint:

    var Books = Backbone.Collection.extend({
      url: '/books'
    });
    

    The Collection and Model components together form a direct mapping of REST resources using the following methods:

    GET  /books/ .... collection.fetch();
    POST /books/ .... collection.create();
    GET  /books/1 ... model.fetch();
    PUT  /books/1 ... model.save();
    DEL  /books/1 ... model.destroy();
    

    When fetching raw JSON data from an API, a Collection will automatically populate itself with data formatted as an array, while a Model will automatically populate itself with data formatted as an object:

    [{"id": 1}] ..... populates a Collection with one model.
    {"id": 1} ....... populates a Model with one attribute.
    

    However, it's fairly common to encounter APIs that return data in a different format than what Backbone expects. For example, consider fetching a Collection from an API that returns the real data array wrapped in metadata:

    {
      "page": 1,
      "limit": 10,
      "total": 2,
      "books": [
        {"id": 1, "title": "Pride and Prejudice"},
        {"id": 4, "title": "The Great Gatsby"}
      ]
    }
    

    In the above example data, a Collection should populate using the "books" array rather than the root object structure. This difference is easily reconciled using a  parse method that returns (or transforms) the desired portion of API data:

    var Books = Backbone.Collection.extend({
      url: '/books',
      parse: function(data) {
        return data.books;
      }
    });
    

    View Rendering

    View rendering.

    Each View manages the rendering and user interaction within its own DOM element. If you're strict about not allowing views to reach outside of themselves, it helps keep your interface flexible — allowing views to be rendered in isolation in any place where they might be needed.

    Backbone remains unopinionated about the process used to render View objects and their subviews into UI: you define how your models get translated into HTML (or SVG, or Canvas, or something even more exotic). It could be as prosaic as a simpleUnderscore template, or as fancy as the React virtual DOM. Some basic approaches to rendering views can be found in the Backbone primer.

    Routing with URLs

    Routing

    In rich web applications, we still want to provide linkable, bookmarkable, and shareable URLs to meaningful locations within an app. Use the Router to update the browser URL whenever the user reaches a new "place" in your app that they might want to bookmark or share. Conversely, the Router detects changes to the URL — say, pressing the "Back" button — and can tell your application exactly where you are now.

    Getting Started

    当在做一个包括大量的JavaScript的web应用程序时,你要学的第一件事就是停止给DOM附加数据。通过复杂多变的jQuery选择符和回调函数很容易创建Javascript应用程序,包括在HTML UI,Javascript逻辑和数据之间保持同步,都不复杂。 但对富客户端应用来说,良好的架构通常是有很多益处的。

    通过Backbone,你可以将数据呈现为 Models, 你可以对模型进行创建,验证和销毁,以及将它保存到服务器。 任何时候只要UI事件引起模型内的属性变化,模型会触发"change"事件; 所有显示模型数据的 Views 会接收到该事件的通知,继而视图重新渲染。 你无需查找DOM来搜索指定id的元素去手动更新HTML。 — 当模型改变了,视图便会自动变化。

    某种意义上说,在用javaScript来创建web项目时,Backbone试图定义一组最小而高效的集合,包括了数据结构(models(模型) 和 collections(集合))和用户接口(views(视图) 和 URLS)。在web开发环境里,到处都是框架(帮你写好了一切),不过这些库需要你的网站在构建的时候符合该框架的样子,风格,默认的行为。但是,Backbone还是作为一个工具,让你可以随心所欲的设计你的网站。

    如果你是新来的,还不太清楚什么是Backbone ,先运行一下 列表中基于Backbone的项目。

    Models and Views

    Model-View Separation.

    Backbone 最基本也是最重要的功能就是可以帮助你让你的业务逻辑分开你的用户界面。当两者相互纠缠,改变是很困难的;当逻辑不依赖于用户界面,界面就会变得容易处理。

    Model
    • 协调数据和业务逻辑。
    • 从服务器加载和保存。
    • 当数据发生变化时发出事件event。
    View
    • 监听变化和呈现UI。
    • 处理用户的输入和交互。
    • 发送捕获的输入到模型中。

    模型管理着内部的数据属性表,并当它的任何数据修改时触发“change”活动。模型有一个很持久的层在处理同步数据——通常是一个REST API支持的数据库。把你的模型设计成不可分割的可重用的对象包含所有有用的函数操纵他们的特定的数据。模型应该能够被传递在你的应用程序,并可以被使用在任何数据是必要的地方。


    视图是一个不可分割的用户界面。它通常从一个特定的或多个的模型中呈现数据, 但它也可以在使用较少数据的模块中作为UI独立存在。模型应该通常不用管视图中的内柔是什么。反而,它只要listen模型中的“change”事件来适当地反应或者重新呈现自己。

    Collections

    Model Collections.

    Collection帮助你处理一组相关的模型,处理新模型的从服务器加载和保存处理服务器和提供辅助函数来执行聚合或计算一系列的模型。除了自己的事件,collection也代理所有模型发生过的事件的集合,允许你在一个地方听到可能发生在任何模型集合中的任何变化。

    API Integration

    预先配置Backbone 来同步RESTful API。简单地创建一个有url端点集合的新Collection 资源:

    var Books = Backbone.Collection.extend({
      url: '/books'
    });

    Collection 和 Model 组件组成的组合直接映射REST资源,使用了以下的方法:

    GET  /books/ .... collection.fetch();
    POST /books/ .... collection.create();
    GET  /books/1 ... model.fetch();
    PUT  /books/1 ... model.save();
    DEL  /books/1 ... model.destroy();

    当从一个API获取原始JSON数据, Collection 将自动填充数据将自己格式化为一个数组,而 Model 将自动填充数据将自己格式化为一个对象:

    [{"id": 1}] ..... populates a Collection with one model.
    {"id": 1} ....... populates a Model with one attribute.

    然而,常常遇到返回数据和Backbone 预期的格式不同的的api。例如,考虑获取 Collection  的API却返回了从元数据得到的真实的数据数组:

    {
      "page": 1,
      "limit": 10,
      "total": 2,
      "books": [
        {"id": 1, "title": "Pride and Prejudice"},
        {"id": 4, "title": "The Great Gatsby"}
      ]
    }

    在上面的示例数据中, Collection  应该使用“books”数组填充,而不是根对象结构。这种差异很容易解决,只要使用 parse 方法,就可以得到返回(或变换)所需的API的一部分数据:

    var Books = Backbone.Collection.extend({
      url: '/books',
      parse: function(data) {
        return data.books;
      }
    });

    View Rendering

    View rendering.

    每个 View  管理呈现在自己的DOM元素和用户交互。如果你严格到不允许视图到达除了自己以外的地方,这么做会有助于保持你的接口灵活---允许视图呈现在他们本来可能需要被隔离的任何地方。


    Backbone 仍然对这个过程不是很固执,它通常将 View 对象和它们的子视图用来渲染UI: 你自己来定义如何将你的模型转换成HTML(或SVG或Canvas,或更特殊的)。它可能像简单的Underscore模板一样乏味, 或虚拟DOM一样有趣。一些基本的呈现视图的方法可以在Backbone底层被发现。

    Routing with URLs

    Routing

    在丰富的web应用程序中,我们仍然需要提供可链接、书签似的、可共享的URL来使一个app中的locations有意义。使用 Router  来使每当用户在你的应用程序到达一个新的他们可能想要收藏或分享的“place”时就更新浏览器URL。相反, Router  检测到更改URL——比如说按“返回”按钮 -- 可以确切地告诉你的应用程序现在你在哪里。

     

     

  • 相关阅读:
    beego 注解路由无效问题分析
    sync.Map实现分析
    由浅入深聊聊Golang的sync.Map
    Go语言编程:使用条件变量Cond和channel通道实现多个生产者和消费者模型
    golang 的 channel 实现 生产者/消费者 模型
    Golang sync.NewCond条件锁的用法
    golang channel多生产者和多消费者实例
    Go语言的那些坑
    go语言标准库sync/atomic中的原子操作
    理解 Go 标准库中的 atomic.Value 类型
  • 原文地址:https://www.cnblogs.com/neuscx/p/5210447.html
Copyright © 2011-2022 走看看