Home Web Front-end JS Tutorial Some suggestions for using JavaScript's Backbone.js framework_Basic knowledge

Some suggestions for using JavaScript's Backbone.js framework_Basic knowledge

May 16, 2016 pm 03:15 PM
backbone dom javascript

Backbone provides a structure of models, collections, and views for complex Javascript applications. The model is used to bind key-value data and custom events; the collection is equipped with a rich API of enumerable functions; the view can declare event handling functions and connect to the application through a RESTful JSON interface.
When developing web applications that contain a lot of JavaScript, one of the first things you need to do is stop appending data to DOM objects. Create Javascript applications with complex jQuery selectors and callback functions, including maintaining synchronization between HTML UI, Javascript logic and data, without any complexity. But for client applications, good architecture often has many benefits.
Backbone presents data as models, and you can create models, validate and destroy them, and even save them to the server. When changes in the UI cause model properties to change, the model will trigger the "change" event; all views that display model data will receive notification of this event, and then the views will be re-rendered. You don't need to search the DOM for the element with a specific id to update the HTML manually. —Once the model changes, the view changes automatically.
backbone.js provides a web development framework, using Models for key-value binding and custom event processing, using Collections to provide a rich set of APIs for enumeration functions, and using Views for event processing and integration with existing Application interacts through the RESTful JSON interface. It is a js framework based on jquery and underscore.

Backbone is not opinionated by nature. The most basic idea you get from the documentation is: use the tools provided by backbone.js to do whatever you want.

This is great because there are so many different use cases and it’s very easy to start writing apps. This approach may prevent us from making as few mistakes as possible when starting out.

When something is wrong, we have to discover it and find a way to correct it.

The following tips can help you avoid the errors we encountered when developing Backbone.js:

1. Views are Data-Less

Data belongs to models (models) not views. Next time you find yourself storing data in a view (or worse: in the DOM), move it into the model immediately.

If you don’t have a model, creating one is very simple:

this.viewState = new Backbone.Model();

Copy after login

Nothing else really needs to be done.

You can listen for change events on your data and even sync it online with your server.

2. DOM events only change models

When a DOM event is triggered, such as clicking a button, don't let it change the view itself. Change this model.

Changing the DOM without changing the state means that your state is still stored in the DOM. This rule keeps you consistent.

If a "Load More" edge is clicked, do not expand the view, just change the model:

this.viewState.set('readMore', true);

Copy after login

Okay, but when does the view change? Good question, answered by the next rule.

3.DOM only changes when the model changes

Events are amazing, please use them. The simplest way is to trigger it after each change.

this.listenTo(this.stateModel, 'change', this.render);

Copy after login

A better approach is to trigger changes only when needed.

this.listenTo(this.stateModel, 'change:readMore', this.renderReadMore);

Copy after login

This view will always remain consistent with its model. This view will always be updated no matter how the model changes: in response to actions from the command interface or debugging information.

4. Bound things must be unbound

When a view is removed from the DOM, using the 'remove' method, it must be unbound from all bound events.

If you use 'on' to bind, your responsibility is to use 'off' to unbind. Without unbinding, the memory collector cannot free the memory, causing your application's performance to degrade.

This is where 'listenTo' comes from. It tracks the binding and unbinding of views. Backbone will perform 'stopListening' before moving this from the DOM.

// Ok:
this.stateModel.on('change:readMore', this.renderReadMore, this);
 
// 神奇:
this.listenTo(this.stateModel, 'change:readMore', this.renderReadMore);

Copy after login


5. Keep chain writing

Always return 'this' from render and remove methods. This allows you to write method chains.

view.render().$el.appendTo(otherElement);

Copy after login

This is the method, don’t break it.

6. Events are better than callbacks

Waiting for a response event is better than calling back

Backbone models trigger 'sync' and 'error' events by default, so these events can be used instead of callbacks. Consider these two scenarios.

model.fetch({
 success: handleSuccess,
 error: handleError
});
//这种更好:
view.listenTo(model, 'sync', handleSuccess);
view.listenTo(model, 'error', handleError);
model.fetch();

Copy after login

It doesn’t matter when the model is fetched, handleSucess/handleError will be called.

7. Views have scope

A view should never manipulate the DOM other than itself.

view will reference its own DOM element, such as 'el' or jquery object '$el'

That means you should never use jQuery directly:

$('.text').html('Thank you');

Copy after login

Please limit the selection of DOM elements to your own domain:

this.$('.text').html('Thank you');
 
// 这等价于
// this.$el.find('.text').html('Thank you');

Copy after login

如果你需要更新一个别的不同的视图,只要触发一个事件,让别的视图去做。你也可以使用Backbone的全局Pub/Sub系统。

例如,我们阻止页面滚动:

var BodyView = Backbone.View.extend({
 initialize: function() {
  this.listenTo(Backbone, 'prevent-scroll', this.preventScroll);
 },
 
 preventScroll: function(prevent) {
  // .prevent-scroll 有下面的CSS规则: overflow: hidden;
  this.$el.toggleClass('prevent-scroll', prevent);
 }
});
 
// 现在从任何其他地方调用:
Backbone.trigger('prevent-scroll', true);  // 阻止 scrolling
Backbone.trigger('prevent-scroll', false); // 允许 scrolling

Copy after login

还有一件事

只要读读backbone的源代码,你会学到更多。看一看backbone.js的源代码,然后看看这些神奇的事情是怎么实现的。这个库非常小,而且可读性很好,整个读完不会超过10分钟的。

这些小贴士帮助我们写干净的,更好的可读的代码。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles