Seajs + backbone Enables automatic loading of single page application modules

Source: Internet
Author: User
Tags autoload string to json

This is not an article about seajs and backbone.ArticleIf you are not familiar with these two databases, you can go to their official website to check them. Welcome to reprint, indicate the source: http://www.cnblogs.com/mapping/archive/2013/03/03/2941812.html

The business logic of a single page application (SPA: single page application) is mostly complicated. If the file used by the whole spa is added at one time, it is estimated that it will not work, using seajs can achieve On-Demand Loading. Using backbone can easily achieve data, logic, and performance separation. Someone calls it the front-end MVC framework, some people say that it is not MVC, so we will not discuss it here.

This article mainly explains how to use these two libraries to automatically load the modules in the spa according to the routes.

First, create the file structure of the entire app,

Root directory: autoload;

Index.html in the root directory is used as the homepage and portal of the app. js files of the app are stored in the JS directory;

Base in the JS directory places the basic dependent JS library, and the main directory places the app frameworkCodeThe Module Directory is used to place the functional Js of each module;

The next step is to package underscore, jquery, and backbone source code into amd standard files. underscore and backbone have built-in amd interfaces, and AMD exports interfaces have been added to the latest jquery versions, if the old version of jquery requires return $. noconfilt (true), as follows:

Base/jquery. js

Define ('base/jquery ',Function(Require ){//Official jquery source codeReturn$. Noconflict (True);});

Base/underscore. js

 
Define ('base/underscore ',Function(Require, exports, module ){//Underscore official source code});

Base/backbone. js

Define ('base/backone', ['underscore ',' $ '],Function(Require, exports, module ){This. _ = Require ('underscore');This. Jquery = require ('$');//Official backbone source code});

 

People who have used backbone know that it is very convenient to use its routing function for spa, and there are few pages. If there are more pages, change the routing configuration each time; although backbone supports multiple router objects, you need to maintain multiple files each time you add a module without adding the corresponding router rules. In addition, the more router configured, the probability of repetition increases, so we need to develop a unified router rule to implement automatic module loading. In fact, we need to pass the module's function file path and file name as parameters to the router processing function, then use require of seajs. the async method loads the corresponding file as follows:

Main/APP. js

Define ('main/app ', Function  (Require, exports ){ VaR Backbone = require ('background' );  //  Configure routes      VaR Autorouter = Backbone. Router. Extend ({routes :{ '': 'Home' , 'At/: module/: Action (/* condition) ': 'loadmodule' }, Home:  Function  (){  This . Loadmodule ('home', 'index' );}, //  Perform auto-Increment Based on the AT/module/Action (/conditions) Format Loadmodule: Function  (MD, AC, con ){  //  Convert the parameter string 'a: 123/B: 456 'To a json object {A: 123, B: 456}              VaR Cj = {};  If (Con & con. indexof (':')>-1 ) {Con. Replace ( /(\ W +) \ s *: \ s * ([\ W-] +)/g, Function  (A, B, C) {B & (CJ [B] = C );});}  Else  {CJ = Con ;}  //  Load the corresponding module under the Module Directory Require. async (['module', MD, AC]. Join ('/'), Function  (Cb ){  If  (Cb) {CB (CJ );}  Else  {Alert ( 'Module failure and loss! ');}})}});  //  Define global variable app Window. APP = {Models :{}, views :{}, collections :{}, initialize:  Function  (){  New  Autorouter (); backbone. History. Start () ;}}; exports. Run = App. initialize ;}) 

Here we give the route a very YY name at (@ out module ^_^), any matching 'at/: module/: Action (/* condition) 'Both the rule paths call the loadmodule method. Here, condition is an optional parameter. To pass multiple parameters, you can write them in the format of 'a: 123/B: 8080, the loadmodule method converts the format string to JSON to facilitate code calls in the module.

There is also an empty route in the autorouter object for app startup. The actual route is equivalent to 'at/home/Index'. What we need to do now is add the module file to the module directory:

Module/home/index. js

Define ('module/home/Index', ['background'], Function  (Reuqire ){  VaR Backbone = reuqire ('background' ); App. Models. Home = Backbone. model. Extend ({}); app. Collections. Home = Backbone. collection. Extend ({model: App. Models. Home}); app. Views. Home = Backbone. View. Extend ({El: '# Iner' , Initialize: Function  (C ){  This . Collections = C;  This  . Render () ;}, render:  Function  (){  VaR Html ='' ;  This . Collections. Each ( Function  (M) {html + = '<Div> <a href = "' + M. get ('link') + '">' + M. get ('name') + '</a> </div>' ;});  This  .Cancel.html (HTML );}})  Return   Function  (){  //  Analog data          VaR Hc = New  App. Collections. Home (); HC. Add ([{ 'Name': 'Load module A', 'link': '# At/M/A/Name: modulea/Other: Nothing' },{ 'Name': 'Load module B ', 'link':' # At/M/B' }]);  New  App. Views. Home (HC );}}); 

Note: Each automatically loaded module must return a function for the loadmodule method callback. Otherwise, the module loading fails;

Pipeline Code:

Index.html

 <!  Doctype html  >  <  Html  >  <  Head  >     <  Meta  Charset  = "UTF-8"  >      <  Title  > Seajs + backbone Enables automatic loading of single page modules </  Title  >  </  Head  >  <  Body  >     <  Div  ID  = "Container"  >      </  Div  >      <  Script  Type  = "Text/JavaScript"  SRC  = "JS/base/sea. js"  > </  Script  >     <  Script  Type  = "Text/JavaScript"  >  Seajs. config ({base:  '  /JS/  '  , Alias :{  //  Basic Library              ' Underscore  '  :  '  Base/underscore  '  ,  '  $  '  :  ' Base/jquery  '  ,  '  Backbone  '  :  '  Base/Backbone  '  ,  ' App  '  :  '  Main/APP  '  }); Seajs. Use (  '  App  '  ,  Function (APP) {app. Run ();});  </  Script  >  </  Body  >  </  Html  > 

Now, the entire app can run.

However, if you click "load module A" or "load Module B", the module fails to be loaded because we have not added the two modules.

Module/M/A. js

Define ('module/M/A', ['$'],Function(Reuqire ){VaR$ = Reuqire ('$');Return Function(C) {alert ('Lelea loaded successfully, parameter: '+$. Param (c ));}});

Load module A running result:

 

Module/M/B. js

 
Define ('module/M/B ', [' $ '],Function(Reuqire ){Return Function(C) {alert ('Leleb loaded successfully, parameter: '+C );}});

Load Module B running result:

 

Now, the entire demo is over. This article just briefly introduces the idea of automatic module loading.

For a complete spa, the style CSS files and template HTML files that the module depends on need to be loaded and the data is pulled from the API. These functions can be easily implemented using seajs and backbone, loading the template HTML file you may need the seajs plugin-text.js plug-in

 

Download the demo package: autoload.zip

 

Welcome to reprint, indicate the source: http://www.cnblogs.com/mapping/archive/2013/03/03/2941812.html

 

 

 

 

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.