Some suggested uses of JavaScript's ES1en. js framework

  • 2020-12-19 20:53:50
  • OfStack

Backbone provides the structure of models (models), collections (collections), and views (views) for complex Javascript applications. Where the model is used to bind key-value data and custom events; Collection with enumerable functions rich API; Views can declare event handlers and connect to applications via the RESTful JSON interface.
When developing an web application with a lot of Javascript, one of the first things you need to do is stop attaching data to the DOM object. Creating Javascript applications with complex and variable jQuery selectors and callbacks, including synchronization between HTML UI, Javascript logic and data, is uncomplicated. But when it comes to client-side applications, good architecture often has many benefits.
Backbone presents the data as a model, which you can create, validate, destroy, and even save to the server. When the change of UI causes the change of model attributes, the model will trigger the "change" event. All views that display the model data receive a notification of this event and the view rerenders. You don't need to look up DOM to search for the element that specifies id to manually update HTML. Once the model changes, the view changes automatically.
backbone.js provides a set of web development framework for key-ES31en binding and custom event handling via Models, a rich set of API for enumeration functions via Collections, event handling via Views and interaction with the existing Application via RESTful JSON interface. It is an js framework based on jquery and underscore.

Backbone is not by nature opinionated. One of the most basic ideas you get from the documentation is this: Use the tools provided by ES45en.js to do whatever you want.

This is great because there are so many different applications, and it's easy to start writing app. This approach may prevent us from making as few mistakes as possible in the beginning.

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

Here are some tips to help you avoid the errors we encountered when developing ES54en.js:

1. View (Views) is data independent (ES59en-ES60en)

The data belongs to the model (models) and not to the view. The next time you find yourself storing data in 1 view (or worse: in DOM), move it to model immediately.

If you don't have model, creating 1 is very easy:


this.viewState = new Backbone.Model();

You really don't need anything else.

You can listen for change events on your data and even synchronize them online with your server.

2. DOM event only changes models

When an DOM event is triggered, say by clicking a button, do not let it change view itself. Change this model.

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

If you click 1 "Load More" edge, do not expand the view, just change model:


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

Okay, but when does the view change? Good question, the next rule will answer.

3.DOM changes only when model changes

Events are magical, please use them. The easiest way to do this is to trigger it 1 time after each change.


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

A better approach is to trigger changes only when they are needed.


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

This view will remain 1 straight to its model. No matter how the model changes: in response to actions from the command interface or debug messages, this view stays up to date.

4. Things that are bound must be unbound

When the view is removed from DOM, use the 'remove' method, which must be unbound from all bound events.

If you use 'on' binding, your job is to use 'off' to unbind. Without unbunching, the memory collector can't free memory, which can degrade the performance of your application.

That's where 'listenTo' comes from. It tracks the binding and unbinding of the view. Backbone 'stopListening' before moving this from DOM.


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


5. Keep the chain

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


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

That's a good way. Don't break it.

6. Events are better than callbacks

It is better to wait for a response event than to call back

The Backbone model (models) fires 'sync' and 'error' events by default, so these events can be used instead of callbacks. So let's think about 1 of these two cases.


model.fetch({
 success: handleSuccess,
 error: handleError
});
// This is better: 
view.listenTo(model, 'sync', handleSuccess);
view.listenTo(model, 'error', handleError);
model.fetch();

It doesn't matter when model fills (fetched), handleSucess/handleError is called.

7. Views is scoped

The view should never operate on DOM other than itself.

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

That means you should never use jQuery directly:


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

Limit the selection of DOM elements to your own domain:


this.$('.text').html('Thank you');
 
//  This is equivalent to 
// this.$el.find('.text').html('Thank you');

If you need to update an individual different view, just fire an event and let the other view do it. You can also use Backbone's global Pub/Sub system.

For example, we block page scrolling:


var BodyView = Backbone.View.extend({
 initialize: function() {
  this.listenTo(Backbone, 'prevent-scroll', this.preventScroll);
 },
 
 preventScroll: function(prevent) {
  // .prevent-scroll  Have the following CSS Rules:  overflow: hidden;
  this.$el.toggleClass('prevent-scroll', prevent);
 }
});
 
//  Now call from anywhere else :
Backbone.trigger('prevent-scroll', true);  //  stop  scrolling
Backbone.trigger('prevent-scroll', false); //  allow  scrolling

One more thing

Just read the backbone source code and you'll learn more. Take a look at the source code for ES188en.js and see how all this magic happens. The library is very small and readable, and the entire reading will not take more than 10 minutes.

These tips help us write clean, better readable code.


Related articles: