Super simple implementation of JavaScriptMVC style framework _ javascript skills

Source: Internet
Author: User
This article will share with you how to implement the javascriptMVC style framework simply and effectively written by foreign friends. I hope you will like it. Introduction

People who have used JavaScript frameworks (such as AngularJS, Backbone, or Ember) are familiar with the working mechanism of mvc in the UI (user interface, front-end. These frameworks implement MVC, making it easier to change the view as needed on a single page. The core concept of Model-View-controller (mvc) is: the controller that processes incoming requests, the view of displayed information, and the model that represents business rules and data access.

Therefore, when you need to create an application that requires switching between different content on a single page, we usually choose to use one of the above frameworks. However, if we only need a framework to implement view switching in a url without additional bundling functions, we do not need to use complicated frameworks such as Angular and Ember. This article tries to use simple and effective methods to solve the same problem.

Concept

The code in the application uses "#" in urls to implement the MVC mode navigation. The application starts with a default url, loads the application view based on the hash value code, and applies the object-model to the view template.

The url format is as follows:

Http: // Domain Name/index.html #/Route Name

The View content must be bound to the value and attribute of the object model in the form of {Property-Name. The code looks for this special template format and replaces the attribute values in the object model.

A view asynchronously loaded in ajax mode is placed in a placeholder of the page. A view placeholder can be any element (ideally p), but it must have a special attribute, and the code locates it based on this special attribute, this also facilitates code implementation. When the url changes, this scenario is repeated and another view is loaded. It sounds simple! The following flowchart explains the message redirection in this specific implementation.

Write code

We started with the basic module design model, and finally exposed our libs to the global scope using the facade design model.

;(function(w,d,undefined){//restofthecode})(window,document);

We need to store the view element in a variable so that it can be used multiple times.

var_viewElement=null;//elementthatwillbeusedtorendertheview

We need a default route to cope with the absence of routing information in the url, so that the default view can be loaded instead of displaying blank pages.

var_defaultRoute=null;

Now let's create the construction method of our main MVC object. We will store the route information in "_ routeMap ".

var jsMvc = function () {  //mapping object for the routes  this._routeMap = {};}

It is time to create a route object. We will store the routing, template, and controller information in this object.

var routeObj = function (c, r, t) {  this.controller = c;  this.route = r;  this.template = t;}

Each url has a special route object routeObj. All these objects will be added to the _ routeMap object, so that we can get them through key-value later.

To add route information to MVC libs, We need to expose a method in libs. So let's create a method, which can be used by the respective controllers to add new routes.

jsMvc.prototype.AddRoute = function (controller, route, template) {  this._routeMap[route] = new routeObj(controller, route, template);}

Method AddRoute receives three parameters: controller, route, and template ). They are:

Controller: the controller is used to access a specific route.

Route: route. This is the part after # in the url.

Template: This is an external html file. It is loaded as the routing view. Now our libs needs an entry point to parse the url and provide services for the associated html template page. To accomplish this, we need a method.

The Initialize method does the following:

1) Get the initialization of view-related elements. The Code requires an element with the view attribute, which can be used to search the HTML page:

2) set the default route

3) Verify that the view elements are reasonable

4) bind a window hash change event. When different hash values of the url change, the view chart can be updated in a timely manner.

5) Finally, start mvc

//Initialize the Mvc manager object to start functioningjsMvc.prototype.Initialize = function () {  var startMvcDelegate = startMvc.bind(this);   //get the html element that will be used to render the view   _viewElement = d.querySelector('[view]');      if (!_viewElement) return; //do nothing if view element is not found     //Set the default route  _defaultRoute = this._routeMap[Object.getOwnPropertyNames(this._routeMap)[0]];     //start the Mvc manager  w.onhashchange = startMvcDelegate;  startMvcDelegate();}

In the above Code, we created a proxy method startMvcDelegate from the startMvc method. When the hash value changes, this proxy will be called. The following is the sequence of operations when the hash value changes:

1) obtain the hash value

2) obtain the route value from the hash

3) obtain the routeObj from the route map object routeMap.

4) if there is no route information in the url, You need to obtain the default route object.

5) Finally, call the Controller related to the route and provide services for the view element.

All the steps above are implemented by the startMvc method below.

//function to start the mvc supportfunction startMvc() {  var pageHash = w.location.hash.replace('#', ''),    routeName = null,    routeObj = null;               routeName = pageHash.replace('/', ''); //get the name of the route from the hash      routeObj = this._routeMap[routeName]; //get the route object     //Set to default route object if no route found  if (!routeObj)    routeObj = _defaultRoute;     loadTemplate(routeObj, _viewElement, pageHash); //fetch and set the view of the route}

Next, we need to use the xml http request to asynchronously load the appropriate view. Therefore, we will pass the value and view element of the route object to the method loadTemplate.

//Function to load external html datafunction loadTemplate(routeObject, view) {  var xmlhttp;  if (window.XMLHttpRequest) {    // code for IE7+, Firefox, Chrome, Opera, Safari    xmlhttp = new XMLHttpRequest();  }  else {    // code for IE6, IE5    xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');  }  xmlhttp.onreadystatechange = function () {    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {      loadView(routeObject, view, xmlhttp.responseText);    }  }  xmlhttp.open('GET', routeObject.template, true);  xmlhttp.send();}

Currently, only views are loaded and the object model is bound to the view template. We will create an empty model object and pass the model related to the method to wake up the route controller. The updated model object is bound to the HTML template in the previously loaded XHR call.

The loadView method is used to call the Controller method and prepare model objects.

The replaceToken method is used to bind a model with an HTML template.

//Function to load the view with the templatefunction loadView(routeObject, viewElement, viewHtml) {  var model = {};    //get the resultant model from the controller of the current route   routeObject.controller(model);    //bind the model with the view    viewHtml = replaceToken(viewHtml, model);      //load the view into the view element  viewElement.innerHTML = viewHtml; } function replaceToken(viewHtml, model) {  var modelProps = Object.getOwnPropertyNames(model),       modelProps.forEach(function (element, index, array) {    viewHtml = viewHtml.replace('{{' + element + '}}', model[element]);  });  return viewHtml;}

Finally, we expose the plug-in outside the global scope of js.

//attach the mvc object to the windoww['jsMvc'] = new jsMvc();

Now, it is time to use this MVC plug-in our single-page application. In the next code segment, the following functions are implemented:

1) introduce this code to the web page

2) Add routing information and view template information with the Controller

3) create a controller

4) initialize lib.

In addition to the link we need above, we can navigate to different paths. The view attribute of a container element contains the view template html.

  JavaScript Mvc  
Related Article

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.