


Some suggestions for using JavaScript's Backbone.js framework_Basic knowledge
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分钟的。
这些小贴士帮助我们写干净的,更好的可读的代码。

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download
The most popular open source editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment