Front-end programming Improvement Journey (VII)----Marionette implementation TODOMVC

Source: Internet
Author: User
Tags addall

Marionettejs is a more concise operation on the basis of Backbonejs, the usual development of the main use of several concepts related to the view: CollectionView, Compositeview, Itemview, Layoutview. The most widely used of these concepts is itemview. The convenience of itemview with respect to view in backbone is that instead of explicitly defining the Render method, the Itemview itself finishes rendering the data to the template and appends the view to El, thus reducing the number of process operations.
At the same time Marionettejs has many events and callback methods such as: Onbeforerender, OnRender, Onbeforedestroy, OnDestroy, onshow, etc. These callback functions are called to execute before or after the corresponding pre-execution, which helps the developer set up a common method of timing, greatly simplifying the business logic implementation.

Of course, this article is not a detailed explanation of marionettejs principle, but for the use of MARIONETTEJS implementation of TODOMVC function (click to download) to explain. As the company according to the specific business needs, in the Marionettejs on the implementation of some packaging, but the basic function Marionettejs not too big, so if you see the code italent No need to panic, just do the idea of understanding can.

First let's look at the project directory, the View directory, and the templates directory:


From the above three directories, compared to the previous article using backbone to achieve TODOMVC does not seem to be much difference, then where is the difference?

The functions provided by each view are mentioned in the previous article:

    • Set El or tagname to define where the view is placed on the previous layer, or the label of the package
    • Set up the corresponding template (templates)
    • Define interaction events, and define interaction functions
    • initialization function (initialize), general setting for collection or model monitoring, for communication between view
    • Render function (render) for rendering data into templates, setting some other global functions
in Marionettejs, the functions performed by various view functions are similar to those described above, except that the above mentioned callbacks in the built-in render and each execution sequence greatly simplify development. In addition, the views of the atoms are not much changed. The emphasis here is on Appview:
Talent.Layout.extend ({//layout uses regionmodel:new Talent.model (), template:jst[' About/app-page '],initialize: function () {this.collection = new Todos ([{title: ' Ada '}, {title: ' Oman '}, {title: ' Come '}]); Initializing the collection facilitates debugging This.listento (This.collection, "add", This.addone); This.listento (This.collection, "all", This.redraw); Monitor collection changes, perform add and redraw},//Redraw here to adjust the logic Regionsclass for partial content display or hide: {input:inputview,list:todoview,toggleall: Toggleallview,status:statusview},//The Regionsclass shorthand class regions used here: {//main: '. Page-main-region ' Todoapp: ' # Todo-header ', Toggleall: ' #todo-toggleall ', Status: ' #todo-footer '//todolist: ' #todo-list '},//regions part of the abbreviated element UI: {// Item: '. Ui-item '},events:function () {var events = {};//events[' click ' + this.ui.item] = ' eventHandler '; return events;} , Onrender:function () {},onshow:function () {var self=this;this.todoapp.show (new This.regionsClass.input ({collection : This.collection}); Toggleall.show (New This.regionsClass.toggleAll ({collection:this.collection})); This.addall (); has been rendered again to display all initialization data this.addstatus (); if (this.collection.length) {$ ("#main"). Show ();}; This is used to initialize the display collection data},//OnShow used for the application template display, the logic used. Redraw:function () {if (this.collection.length==0) {This.flag = true;} if ((this.collection.length>=1) &&this.flag) {this.addstatus (); this.flag = false;} By setting a flag property, mark when collection is empty to have a value, and then re-show the Statusview procedure if (this.collection.length) {//render when executing the code shown or hidden $ ("#mai        N "). Show ();      If collection is empty, footer} else {$ ("#main") is emptied. Hide (); }},//To monitor collection changes at all times, show or hide some regionaddstatus:function () {var statusview = new This.regionsClass.status ({collection: This.collection,model:new Talent.model ({done:this.collection.done (). Length, Remaining:this.collection.re Maining (). length, length:this.collection.length}); This.status.show (Statusview);},//Add status bar view Addone:functio N (Todo) {var listItem = new This.regionsClass.list ({Model:todo}); Listitem.render (); $ ("#todo-list"). Append (liStitem. $el);//This adds new entries and renders to Appview},addall:function () {var self = This;_.each (self.collection.models, function (  Item) {Self.addone (item),//collection each to be added to the Appview page)})});

Appview uses the layout class, Layout mixes the Itemview and region concepts, and is ideal for managing multiple sub-views. There are several views below the Appview, which is suitable for layout. layout has several concepts:
Regionsclass: {Input:inputview,list:todoview,toggleall:toggleallview,status:statusview},// The Regionsclass shorthand class used here is regions: {//main: '. Page-main-region ' Todoapp: ' #todo-header ', Toggleall: ' #todo-toggleall ', Status: "#todo-footer"//todolist: ' #todo-list '},//regions part of the shorthand element

  The regionsclass property can set an alias for the introduced class, andtheregions Property sets the alias for the area node to be inserted.
when you need to insert a child view into the specified area of the Appview view, execute the following code:
This.todoApp.show (New This.regionsClass.input ({collection:this.collection}));

here, the Show method works by rendering the child view and placing the El under the regions defined Area node, and the child view is displayed to the Appview specified area. The above mentioned Marionettejs all kinds of views are built into the render, then the use of BACKBONEJS monitoring collection or model changes in the implementation of the This.render is limited, because in addition to loading the data into the template and putting it under El, we may need additional logic along with execution. Le Emperor uses a custom method and does the event monitoring.
Redraw:function () {if (this.collection.length==0) {This.flag = true;} if ((this.collection.length>=1) &&this.flag) {this.addstatus (); this.flag = false;} By setting a flag property, mark when collection is empty to have a value, and then re-show the Statusview procedure if (this.collection.length) {        //render when you execute the show or hide code         $ ("# Main "). Show ();        If collection is empty, then empty footer      } else {        $ ("#main"). Hide ();      },//Time monitor collection change, show or hide part of region

    Event Monitoring:
This.listento (This.collection, "all", This.redraw); Monitor collection changes, perform add and redraw

to make the program more standard, a new way of hiding or showing the view is used, which involves hiding and showing the status sub-view. According to jquery programming, by selecting the specified DOM element, the show and hide method can be resolved. to give full play to data-driven execution, in the Statusview view, when the model length in collection is zero, the view is closed:
Redraw:function () {            if (this.collection.length==0) {                this.close ();            }            var length = this.collection.length;            This.model.set ({                done:this.collection.done (). Length,                remaining:this.collection.remaining (). Length,                length:this.collection.length            });            This.render ();        }

At this point, when the view is closed, the entire view is removed in the DOM and in memory, and when the model in collection is nonzero again, the view needs to be restarted, and a statusview will need to be re-displayed in the Appview. this defines a method for adding Statusview:
Addstatus:function () {var statusview = new This.regionsClass.status ({collection:this.collection,model:new Talent.model ({done:this.collection.done (). Length,                remaining:this.collection.remaining (). length,                length : This.collection.length})}); This.status.show (Statusview);},//Add status bar view

The above method is then introduced in the callback function of the custom listener collection change:
Redraw:function () {if (this.collection.length==0) {This.flag = true;} if ((this.collection.length>=1) &&this.flag) {this.addstatus (); this.flag = false;} By setting a flag property, mark when collection is empty to have a value, and then re-show the Statusview procedure if (this.collection.length) {        //render when you execute the show or hide code         $ ("# Main "). Show ();        If collection is empty, then empty footer      } else {        $ ("#main"). Hide ();      },//Time monitor collection change, show or hide part of region

Note that there is a flag attribute flag, which is used to record collection from empty to add model, which only re-opens the Statusview child view. at this point, related to the adoption of Marionettejs to achieve TODOMVC of the key issues, have been elaborated. more rules than backbone, bringing in less code and using any technology is a trade-off between learning costs and efficient development.

Front-end programming Improvement Journey (VII)----Marionette implementation TODOMVC

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.