Home  >  Article  >  Web Front-end  >  Some suggestions for using JavaScript’s Backbone.js framework_Basic knowledge

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

WBOY
WBOYOriginal
2016-05-16 15:15:461101browse

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();

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);

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);

A better approach is to trigger changes only when needed.

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

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);


5. Keep chain writing

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

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

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();

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');

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

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

如果你需要更新一个别的不同的视图,只要触发一个事件,让别的视图去做。你也可以使用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

还有一件事

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

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

Statement:
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