Frontend programming improvement Tour (4) ---- first experience of backbone

Source: Internet
Author: User
Tags addall smarty template

Frontend programming improvement Tour (4) ---- first experience of backbone

Coming to a new internship organization, the company's business model, organizational structure, development technology, and development specifications are new to cainiao like Le di, during the past few days, I have been familiar with the front-end architecture adopted by the company. The front-end architecture includes backbone, marionette, and requirejs. Ledi learned PHP Technology during his internship in iQiYi, and had an understanding of the smarty template and thinkphp framework. It is still a little basic to access front-end MVC.

The company has a list of professional front-end training processes. This week's main work includes: Reading the brief document of backbone, reading the todoMVC example of backbone, reading the official document of backbone, reading the todoMVC example of backbone, reading the brief introduction of marionette, and following the source code of todoMVC, I wrote the todoMVC code and read the summary article of backbone. I finally figured out the ins and outs of backbone.

Looking back, the best way to improve learning efficiency is: read the introduction of simple concepts, use examples, and read a comprehensive example to absorb simple concepts, read all the APIs in the official documentation, and repeat the integrated examples. This learning sequence follows the principles of understanding and practice. Ledi basically learned the backbone in this order. The comments in the following code snippet are the overall understanding of model, collection, and view.

$ (Function () {var Todo = Backbone. model. extend ({default: function () {return {title: "hello ledi", order: Todos. nextOrder (), done: false };}, toggle: function () {return this. save (done ,! This. get ("done") ;}}); // construct a basic data model and process data TodoList = Backbone. collection. extend ({model: Todo, localStorage: new Backbone. localStorage ("todos-backbone"), done: function () {return this. where ({done: true}) ;}, remaining: function () {return this. where ({done: false}) ;}, nextOrder: function () {if (! This. length) {return 1;} else {return this. last (). get ('order') + 1 ;}}, comparator: 'order'}); // serves as a set of data models, manage models by adding, deleting, searching, sorting, etc. var Todos = new TodoList; var TodoView = Backbone. view. extend ({tagName: "li", template: _.template({'item-template'}.html (), events: {"click. toggle ":" toggleDone "," dblclick. view ":" edit "," click. destroy ":" clear "," keypress. edit ":" updateOnEnter "," blur. edit ":" close "}, // event Definition, Control the interaction part initialize: function () {this. listenTo (this. model, 'change', this. render); this. listenTo (this. model, 'deststroy', this. remove) ;}, // bind the render: function () {this.cancel.html (this. template (this. model. toJSON (); this. $ el. toggleClass ('done', this. model. get ('done'); // switch whether the done class exists. debug and view this class. input = this. $ ('. edit '); return this;}, // initialize the rendering template content, as the display part toggleDone: function () {this. model. toggle (); }, Edit: function () {this. $ el. addClass (". editing "); this. input. focus () ;}, close: function () {var value = this. input. val (); if (! Value) {this. clear ();} else {this. model. save ({title: value}); this. $ el. removeClass (". editing ") ;}}, updateOnEnter: function (e) {if (e. keyCode = 13) {this. close () ;}, clear: function () {this. model. destroy () ;}}); // todoview corresponds to the model one by one. The model data is displayed and interactive. var appView = Backbone. view. extend ({el: $ ("# todoapp"), statsTemplate: _.template('{stats-template'{.html (), // statistics template events: {"keypress # new-todo ":" CreateOnEnter "," click # clear-completed ":" clearCompleted "," click # toggle-all ":" toggleAllComplete "}, // listen to the event initialize: function () {this. input = this. $ ("# new-todo"); this. allCheckbox = this. $ ("# toggle-all") [0]; this. listenTo (Todos, 'add', this. addOne); this. listenTo (Todos, 'reset', this. addAll); this. listenTo (Todos, 'all', this. render); this. footer = this. $ ('footer '); this. main = $ ('# main '); Todos. fetch () ;}, // listens for collection changes, and binds the collection to render: function () {var done = Todos. done (). length; var remaining = Todos. remaining (). length; if (! Todo. length) {this. main. show (); this. footer. show (); this.footer.html (this. statsTemplate ({done: done, remaining: remaining});} else {this. main. hide (); this. footer. hide ();} this. allCheckbox. checked =! Remaining ;}, // The overall display addOne: function (todo) {view = new TodoView ({model: todo}); this. $ ("# todo-list "). append (view. render (). el) ;}, addAll: function () {Todos. each (this. addOne, this); // The collection and model are used here to communicate}, createOnEnter: function (e) {if (e. keyCode! = 13) return; if (! This. input. val () return; Todos. create ({title: this. input. val ()}); this. input. val ('');}, clearCompleted: function (){_. invoke (Todos. done, 'deststroy'); return false;}, toggleAllComplete: function () {var done = this. allCheckbox. checked; Todos. each (function (todo) {todo. save (done, 'done') ;}}}); // as a global view, control the interaction between multiple todoview views and other display modules. var app = new appView;}) // view basic mode: the initial display is performed through initialization and rendering functions, define the event list and write corresponding execution functions for interaction.

The above is the todo example of ledi's research, and I tried it again to understand the functions of each module. The model provides a data model and data processing. The collection is a set of models. It mainly uses the model as the processing object and adds, deletes, searches, sorts, and other operations to it; view is the Controller function in the traditional back-end MVC Architecture. It is mainly responsible for controlling the display and interaction logic.

The overview of the backbone document is not clearly written in subsequent articles. Here, ledi provides a typical example of the view and template to understand the role of view as the core of MVC;

  
 <Script type = "text/template" id = "hello-template"> <% = message %>Toggle</Script>
 <Script type = "text/javascript"> var TestView = Backbone. view. extend ({events: {'click button # toggle ': 'toggle'}, initialize: function () {this. template = _. template ($ ("# hello-template" ).html (); // set the template this. render () ;}, render: function () {this.cancel.html (this. template ({message: "hello world! "}); // Rendering template return this;}, toggle: function () {this. $ ("# hello "). toggle (); return this ;}}); $ (function () {var v = new TestView ({el: $ ('# hello ')});}); // This example shows how to set templates, input parameters, render pages, and add interactive events. It is very helpful to understand the view function: display pages and add interactions. // Http://blog.csdn.net/raptor/article/details/8566017 </script>

The display and interaction provided by this code is very simple, though small and dirty. You can clearly see what the view is to do to display pages and add interactions. The following is an example of model and collection:

Var Foo = Backbone. model. extend ({}); // or initialize the default data var Foo = Backbone. model. extend ({defaults: {name: "hello", value: "233"}); // or assign a value at runtime. // For example, var foo = new Foo ({name: "world", value: "874"}); // or var foo = new Foo; foo. set ({name: "world", value: "874"}); var FooList = Backbone. collection. extend ({model: Foo}); var foos = new FooList; foos. add ([{name: "hello", value: "233" },{ name: "world", value: "874"}]); $ (function () {$ ("# hello "). text (JSON. stringify (foos. at (0 )));;});

This Code provides the basic definition and use of the model and collection. In addition, it also involves addition, deletion, search, validity verification, event binding, and other functions. Because it will involve backend interaction, there are not many topics in ledi. You can stamp me in details.

As for router, it is relatively simple to define routing rules. Ledi's next step is to use requirejs to organize todoMVC code and read marionette to write a todoMVC example, and finally write the MVC example on talentjs to get started with the project.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.