Javascript backbone.js 的目的是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5418369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:07:48  来源:igfitidea点击:

What is the purpose of backbone.js?

javascriptjquerybackbone.js

提问by sushil bharwani

I tried to understand the utility of backbone.js from its site http://documentcloud.github.com/backbone, but I still couldn't figure out much.

我试图从它的站点http://documentcloud.github.com/backbone了解backbone.js 的效用,但我仍然无法弄清楚。

Can anybody help me by explaining how it works and how could it be helpful in writing better JavaScript?

任何人都可以通过解释它是如何工作的以及它如何帮助我编写更好的 JavaScript 来帮助我吗?

采纳答案by Vlad Gurovich

Backbone.js is basically an uber-light framework that allows you to structure your Javascript code in an MVC(Model, View, Controller) fashion where...

Backbone.js 基本上是一个超级轻量级​​的框架,它允许您以MVC(模型、视图、控制器)的方式构建您的 Javascript 代码,其中...

Modelis part of your code that retrieves and populates the data,

模型是检索和填充数据的代码的一部分,

Viewis the HTML representation of this model (views change as models change, etc.)

视图是该模型的 HTML 表示(视图随着模型的变化而变化等)

and optional Controllerthat in this case allows you to save the state of your Javascript application via a hashbang URL, for example: http://twitter.com/#search?q=backbone.js

和可选的控制器,在这种情况下,它允许您通过 hashbang URL 保存 Javascript 应用程序的状态,例如:http: //twitter.com/#search?q=backbone.js

Some pros that I discovered with Backbone:

我在 Backbone 中发现的一些优点:

  • No more Javascript Spaghetti: code is organized and broken down into semantically meaningful .js files which are later combined using JAMMIT

  • No more jQuery.data(bla, bla): no need to store data in DOM, store data in models instead

  • event binding just works

  • extremely useful Underscore utility library

  • backbone.js code is well documented and a great read. Opened my eyes to a number of JS code techniques.

  • 没有更多的 Javascript 意大利面:代码被组织并分解成语义上有意义的 .js 文件,这些文件后来使用 JAMMIT 进行组合

  • 不再jQuery.data(bla, bla):无需将数据存储在 DOM 中,而是将数据存储在模型中

  • 事件绑定正常工作

  • 非常有用的 Underscore 实用程序库

  • backbone.js 代码有很好的文档和很好的阅读。让我对一些 JS 代码技术大开眼界。

Cons:

缺点:

  • Took me a while to wrap my head around it and figure out how to apply it to my code, but I'm a Javascript newbie.
  • 我花了一段时间来思考它并弄清楚如何将它应用到我的代码中,但我是一个 Javascript 新手。

Here is a set of great tutorials on using Backbone with Rails as the back-end:

这里有一组关于使用 Backbone 和 Rails 作为后端的很棒的教程:

CloudEdit: A Backbone.js Tutorial with Rails:

CloudEdit:使用 Rails 的 Backbone.js 教程:

http://www.jamesyu.org/2011/01/27/cloudedit-a-backbone-js-tutorial-by-example/

http://www.jamesyu.org/2011/01/27/cloudedit-a-backbone-js-tutorial-by-example/

http://www.jamesyu.org/2011/02/09/backbone.js-tutorial-with-rails-part-2/

http://www.jamesyu.org/2011/02/09/backbone.js-tutorial-with-rails-part-2/

p.s. There is also this wonderful Collectionclass that lets you deal with collections of models and mimic nested models, but I don't want to confuse you from the start.

ps 还有这个很棒的Collection类,它可以让您处理模型集合并模拟嵌套模型,但我不想从一开始就混淆您。

回答by John Munsch

If you're going to build complex user interfaces in the browser then you will probably find yourself eventually inventing most of the pieces that make up frameworks like Backbone.js and Sammy.js. So the question is, are you building something complicated enough in the browser to merit using it (so you don't end up inventing the same thing yourself).

如果您打算在浏览器中构建复杂的用户界面,那么您可能会发现自己最终会发明构成 Backbone.js 和 Sammy.js 等框架的大部分组件。所以问题是,你是否在浏览器中构建了足够复杂的东西以值得使用它(所以你最终不会自己发明同样的东西)。

If what you plan to build is something where the UI regularly changes how it displays but does not go to the server to get entire new pagesthen you probably need something like Backbone.js or Sammy.js. The cardinal example of something like that is Google's GMail. If you've ever used it you'll notice that it downloads one big chunk of HTML, CSS, and JavaScript when you first log in and then after that everything happens in the background. It can move between reading an email and processing the inbox and searching and back through all of them again without ever asking for a whole new page to be rendered.

如果您计划构建的内容是 UI 定期更改其显示方式但不会转到服务器以获取整个新页面,那么您可能需要类似 Backbone.js 或 Sammy.js 的内容。类似的主要例子是谷歌的 GMail。如果您曾经使用过它,您会注意到它会在您第一次登录时下载一大块 HTML、CSS 和 JavaScript,然后一切都在后台进行。它可以在阅读电子邮件和处理收件箱以及搜索和返回所有电子邮件之间移动,而无需要求呈现全新的页面。

It's that kind of app that these frameworks excel at making easier to develop. Without them you'll either end up glomming together a diverse set of individual libraries to get parts of the functionality (for example, jQuery BBQ for history management, Events.js for events, etc.) or you'll end up building everything yourself and having to maintain and test everything yourself as well. Contrast that with something like Backbone.js that has thousands of people watching it on Github, hundreds of forks where people may be working on it, and hundreds of questions already asked and answered here on Stack Overflow.

正是这些框架擅长使开发更容易的那种应用程序。如果没有它们,您要么最终将各种不同的独立库组合在一起以获得部分功能(例如,用于历史管理的 jQuery BBQ、用于事件的 Events.js 等),要么您最终会自己构建所有内容并且还必须自己维护和测试一切。相比之下,像 Backbone.js 这样的东西在 Github 上有成千上万的人在看它,有数百个人们可能正在研究它的分叉,以及在 Stack Overflow 上已经提出和回答的数百个问题。

But none of it is of any importance if what you plan to build is not complicated enough to be worth the learning curve associated with a framework. If you're still building PHP, Java, or something else sites where the back end server is still doing all the heavy lifting of building the web pages upon request by the user and JavaScript/jQuery is just icing upon that process, you aren't going to need or are not yet ready for Backbone.js.

但是,如果您计划构建的内容不够复杂,不值得学习框架相关的学习曲线,那么这一切都无关紧要。如果您仍在构建 PHP、Java 或其他网站,而后端服务器仍在根据用户的请求执行构建网页的所有繁重工作,而 JavaScript/jQuery 只是为该过程锦上添花,那么您就不是不需要或尚未准备好使用 Backbone.js。

回答by superluminary

Backbone is...

骨干是...

...a very small library of components which you can use to help organise your code. It comes packaged as a single JavaScript file. Excluding comments, it has less than 1000 lines of actual JavaScript. It's sensibly written and you can read the whole thing in a couple of hours.

...一个非常小的组件库,您可以使用它来帮助组织您的代码。它打包为单个 JavaScript 文件。不包括注释,它只有不到 1000 行的实际 JavaScript。它写得很明智,你可以在几个小时内阅读整篇文章。

It's a front-end library, you include it in your web page with a script tag. It only affects the browser, and says little about your server, except that it should ideally expose a restful API.

它是一个前端库,您可以使用脚本标记将其包含在您的网页中。它只影响浏览器,几乎不涉及您的服务器,除了理想情况下它应该公开一个宁静的 API。

If you have an API, Backbone has a few helpful features that will help you talk to it, but you can use Backbone to add interactivity to any static HTML page.

如果您有 API,Backbone 有一些有用的功能可以帮助您与之对话,但您可以使用 Backbone 为任何静态 HTML 页面添加交互性。

Backbone is for...

骨干是为了...

...adding structure to JavaScript.

...向 JavaScript 添加结构。

Because JavaScript doesn't enforce any particular patterns, JavaScript applications can become very messy very quickly. Anyone who has built something beyond trivial in JavaScript will have likely run up against questions such as:

因为 JavaScript 不强制执行任何特定模式,所以 JavaScript 应用程序很快就会变得非常混乱。任何在 JavaScript 中构建过一些不平凡的东西的人都可能会遇到以下问题:

  1. Where will I store my data?
  2. Where will I put my functions?
  3. How will I wire my functions together, so that they are called in a sensible way and don't turn to spaghetti?
  4. How can I make this code maintainable by different developers?
  1. 我将在哪里存储我的数据?
  2. 我将把我的函数放在哪里?
  3. 我将如何将我的函数连接在一起,以便以合理的方式调用它们并且不会变成意大利面?
  4. 如何让不同的开发人员可以维护此代码?

Backbone seeks to answer these questions by giving you:

Backbone 旨在通过为您提供以下信息来回答这些问题:

  • Models and Collections to help you represent data and collections of data.
  • Views, to help you update your DOM when your data changes.
  • An event system so that components can listen to each other. This keeps your components de-coupled and prevents spaghettification.
  • A minimal set of sensible conventions, so developers can work together on the same codebase.
  • 模型和集合可帮助您表示数据和数据集合。
  • 视图,可帮助您在数据更改时更新 DOM。
  • 一个事件系统,以便组件可以相互监听。这可以使您的组件解耦并防止意大利面条化。
  • 一组最小的合理约定,因此开发人员可以在同一个代码库上协同工作。

We call this an MV* pattern. Models, Views and optional extras.

我们称之为 MV* 模式。模型、视图和可选的附加功能。

Backbone is light

脊椎很轻

Despite initial appearances, Backbone is fantastically light, it hardly does anything at all. What it does do is very helpful.

尽管最初出现,Backbone 非常轻,它几乎没有任何作用。它所做的非常有帮助。

It gives you a set of little objects which you can create, and which can emit events and listen to each other. You might create a little object to represent a comment for example, and then a little commentView object to represent the display of the comment in a particular place in the browser.

它为您提供了一组您可以创建的小对象,它们可以发出事件并相互监听。例如,您可以创建一个小对象来表示评论,然后创建一个小 commentView 对象来表示在浏览器中特定位置的评论显示。

You can tell the commentView to listen to the comment and redraw itself when the comment changes. Even if you have the same comment displayed in several places on your page all these views can listen to the same comment model and stay in sync.

您可以告诉 commentView 收听评论并在评论更改时重新绘制自己。即使您在页面上的多个位置显示相同的评论,所有这些视图都可以收听相同的评论模型并保持同步。

This way of composing code helps to keep you from getting tangled even if your codebase becomes very large with many interactions.

即使您的代码库因许多交互而变得非常大,这种编写代码的方式也有助于防止您陷入困境。

Models

楷模

When starting out, it's common to store your data either in a global variable, or in the DOM as data attributes. Both of these have issues. Global variables can conflict with each other, and are generally bad form. Data attributes stored in the DOM can only be strings, you will have to parse them in and out again. It's difficult to store things like arrays, dates or objects, and to parse your data in a structured form.

刚开始时,通常将数据存储在全局变量或 DOM 中作为数据属性。这两个都有问题。全局变量可能会相互冲突,并且通常是不好的形式。存储在 DOM 中的数据属性只能是字符串,您必须重新解析它们。很难存储数组、日期或对象等内容,也很难以结构化形式解析数据。

Data attributes look like this:

数据属性如下所示:

<p data-username="derek" data-age="42"></p>

Backbone solves this by providing a Model object to represent your data and associated methods. Say you have a todo list, you would have a model representing each item on that list.

Backbone 通过提供一个 Model 对象来表示您的数据和相关方法来解决这个问题。假设您有一个待办事项列表,您将有一个模型来表示该列表中的每个项目。

When your model is updated, it fires an event. You might have a view tied to that particular object. The view listens for model change events and re-renders itself.

当您的模型更新时,它会触发一个事件。您可能有一个与该特定对象相关联的视图。视图侦听模型更改事件并重新呈现自身。

Views

观看次数

Backbone provides you with View objects that talk to the DOM. All functions that manipulate the DOM or listen for DOM events go here.

Backbone 为您提供与 DOM 对话的 View 对象。所有操作 DOM 或侦听 DOM 事件的函数都放在这里。

A View typically implements a render function which redraws the whole view, or possibly part of the view. There's no obligation to implement a render function, but it's a common convention.

一个视图通常实现一个渲染函数,它重绘整个视图,或者可能是视图的一部分。没有义务实现渲染功能,但这是一个常见的约定。

Each view is bound to a particular part of the DOM, so you might have a searchFormView, that only listens to the search form, and a shoppingCartView, that only displays the shopping cart.

每个视图都绑定到 DOM 的特定部分,因此您可能有一个只监听搜索表单的 searchFormView 和一个只显示购物车的 shoppingCartView。

Views are typically also bound to specific Models or Collections. When the Model updates, it fires an event which the view listens to. The view might them call render to redraw itself.

视图通常也绑定到特定的模型或集合。当模型更新时,它会触发视图监听的事件。视图可能会调用 render 来重绘自身。

Likewise, when you type into a form, your view can update a model object. Every other view listening to that model will then call its own render function.

同样,当您输入表单时,您的视图可以更新模型对象。侦听该模型的每个其他视图然后将调用其自己的渲染函数。

This gives us a clean separation of concerns that keeps our code neat and tidy.

这为我们提供了一个干净的关注点分离,使我们的代码保持整洁。

The render function

渲染功能

You can implement your render function in any way you see fit. You might just put some jQuery in here to update the DOM manually.

您可以以任何您认为合适的方式实现您的渲染功能。您可能只是在这里放了一些 jQuery 来手动更新 DOM。

You might also compile a template and use that. A template is just a string with insertion points. You pass it to a compile function along with a JSON object and get back a compiled string which you can insert into your DOM.

您也可以编译一个模板并使用它。模板只是一个带有插入点的字符串。您将它与一个 JSON 对象一起传递给一个编译函数,并返回一个编译后的字符串,您可以将其插入到您的 DOM 中。

Collections

收藏

You also have access to collections which store lists of models, so a todoCollection would be a list of todo models. When a collection gains or loses a model, changes its order, or a model in a collection updates, the whole collection fires an event.

您还可以访问存储模型列表的集合,因此 todoCollection 将是一个待办事项模型列表。当集合获得或丢失模型、更改其顺序或集合中的模型更新时,整个集合会触发一个事件。

A view can listen to a collection and update itself whenever the collection updates.

视图可以侦听集合并在集合更新时更新自身。

You could add sort and filter methods to your collection, and make it sort itself automatically for example.

例如,您可以向集合中添加排序和过滤方法,并使其自动排序。

And Events to Tie It All Together

以及将这一切联系在一起的事件

As much as possible, application components are decoupled from each other. They communicate using events, so a shoppingCartView might listenTo a shoppingCart collection, and redraw itself when the cart is added to.

应用程序组件尽可能地相互解耦。它们使用事件进行通信,因此shoppingCartView 可能会监听shoppingCart 集合,并在添加购物车时重绘自身。

shoppingCartView.listenTo(shoppingCart, "add", shoppingCartView.render);

Of course, other objects might also be listening to the shoppingCart as well, and might do other things like update a total, or save the state in local storage.

当然,其他对象也可能正在侦听购物车,并且可能会做其他事情,例如更新总数或将状态保存在本地存储中。

  • Views listen to Models and render when the model changes.
  • Views listen to collections and render a list (or a grid, or a map, etc.) when an item in the collection changes.
  • Models listen to Views so they can change state, perhaps when a form is edited.
  • 视图监听模型并在模型更改时进行渲染。
  • 视图侦听集合并在集合中的项目更改时呈现列表(或网格或地图等)。
  • 模型监听视图以便他们可以改变状态,也许是在编辑表单时。

Decoupling your objects like this and communicating using events means that you'll never get tangled in knots, and adding new components and behaviour is easy. Your new components just have to listen to the other objects already in the system.

像这样解耦您的对象并使用事件进行通信意味着您永远不会陷入困境,并且添加新组件和行为很容易。您的新组件只需要监听系统中已有的其他对象。

Conventions

公约

Code written for Backbone follows a loose set of conventions. DOM code belongs in a View. Collection code belongs in a Collection. Business logic goes in a model. Another developer picking up your codebase will be able to hit the ground running.

为 Backbone 编写的代码遵循一组松散的约定。DOM 代码属于一个视图。集合代码属于一个集合。业务逻辑存在于模型中。另一个拿起你的代码库的开发人员将能够开始运行。

To sum up

总结

Backbone is a lightweight library that lends structure to your code. Components are decoupled and communicate via events so you won't end up in a mess. You can extend your codebase easily, simply by creating a new object and having it listen to your existing objects appropriately. Your code will be cleaner, nicer, and more maintainable.

Backbone 是一个轻量级的库,可以为您的代码提供结构。组件被解耦并通过事件进行通信,因此您不会陷入混乱。您可以轻松扩展您的代码库,只需创建一个新对象并让它适当地侦听您现有的对象。您的代码将更干净、更漂亮且更易于维护。

My little book

我的小书

I liked Backbone so much that I wrote a little intro book about it. You can read it online here: http://nicholasjohnson.com/backbone-book/

我非常喜欢 Backbone,所以我写了一本关于它的介绍书。你可以在这里在线阅读:http: //nicholasjohnson.com/backbone-book/

I also broke the material down into a short online course, which you can find here: http://www.forwardadvance.com/course/backbone. You can complete the course in about a day.

我还将这些材料分解为一个简短的在线课程,您可以在这里找到:http: //www.forwardadvance.com/course/backbone。您可以在大约一天内完成课程。

回答by dpan

Here's an interesting presentation:

这是一个有趣的演示:

An intro to Backbone.js

Backbone.js 简介

Hint (from the slides):

提示(来自幻灯片):

  • Rails in the browser? No.
  • An MVC framework for JavaScript? Sorta.
  • A big fat state machine? YES!
  • 浏览器中的 Rails?没有
  • JavaScript 的 MVC 框架?排序
  • 一个巨大的状态机?是的

回答by Andrew Hare

Backbone.js is a JavaScript framework that helps you organize your code. It is literally a backbone upon which you build your application. It doesn't provide widgets (like jQuery UI or Dojo).

Backbone.js 是一个 JavaScript 框架,可帮助您组织代码。它实际上是您构建应用程序的支柱。它不提供小部件(如 jQuery UI 或 Dojo)。

It gives you a cool set of base classes that you can extend to create clean JavaScript code that interfaces with RESTful endpoints on your server.

它为您提供了一组很酷的基类,您可以扩展这些基类以创建与服务器上的 RESTful 端点接口的干净 JavaScript 代码。

回答by sv_in

JQuery and Mootools are just a toolbox with lot of tools of your project. Backbone acts like an architecture or a backbone for your project on which you can build an application using JQuery or Mootools.

JQuery 和 Mootools 只是一个工具箱,其中包含您项目的许多工具。Backbone 就像一个架构或项目的主干,您可以在其上使用 JQuery 或 Mootools 构建应用程序。

回答by Vince

This is a pretty good introductory video: http://vimeo.com/22685608

这是一个相当不错的介绍视频:http: //vimeo.com/22685608

If you are looking for more on Rails and Backbone, Thoughtbot has this pretty good book (not free): https://workshops.thoughtbot.com/backbone-js-on-rails

如果您正在寻找有关 Rails 和 Backbone 的更多信息,Thoughtbot 有这本不错的书(不是免费的):https://workshops.thoughtbot.com/backbone-js-on-rails

回答by user1415445

I have to admit that all the "advantages" of MVC have never made my work easier, faster, or better. It just makes the whole codeing experience more abstract and time consuming. Maintenance is a nightmare when trying to debug someone elses conception of what separation means. Don't know how many of you people have ever tried to update a FLEX site that used Cairngorm as the MVC model but what should take 30 seconds to update can often take over 2 hours (hunting/tracing/debugging just to find a single event). MVC was and still is, for me, an "advantage" that you can stuff.

我不得不承认 MVC 的所有“优势”从未让我的工作变得更轻松、更快或更好。它只会使整个编码体验更加抽象和耗时。当试图调试别人对分离意味着什么的概念时,维护是一场噩梦。不知道你们中有多少人曾经尝试更新使用 Cairngorm 作为 MVC 模型的 FLEX 站点,但是需要 30 秒才能更新的内容通常需要 2 多个小时(寻找/跟踪/调试只是为了找到单个事件)。对我来说,MVC 过去和现在仍然是您可以填充的“优势”。

回答by anish

Backbone was created by Jeremy Ashkenas who also wrote CoffeeScript. As a JavaScript-heavy application, what we now know as Backbone was responsible for structuring the application into a coherent code base. Underscore.js, backbone's only dependency, was also part of the DocumentCloud application.

Backbone 是由同时编写 CoffeeScript 的 Jeremy Ashkenas 创建的。作为一个 JavaScript 密集型应用程序,我们现在知道的 Backbone 负责将应用程序构建成一个连贯的代码库。Underscore.js 是主干唯一的依赖项,也是 DocumentCloud 应用程序的一部分。

Backbone helps developers manage a data model in their client-side web app with as much disciplineand structureas you would get in traditional server-side application logic.

Backbone 帮助开发人员在他们的客户端 Web 应用程序中管理数据模型,其规则结构与传统服务器端应用程序逻辑中的规则结构一样多。

Additional benefits of using Backbone.js

使用 Backbone.js 的其他好处

  1. See Backbone as a library, not as a framework
  2. Javascript is now getting organized in a structured way, the (MVVM) Model
  3. Large user community
  1. 将 Backbone 视为一个库,而不是一个框架
  2. Javascript 现在以结构化的方式组织起来,(MVVM) 模型
  3. 庞大的用户群