In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail how to use code to implement the JavaScript MVC style framework, the content of the article is of high quality, so the editor will share it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.
Download JavaScript-Mvc.zip-4.6KB
JavaScript Mvc on Github
Live Demo
Introduction
People who have used JavaScript frameworks (such as AngularJS, Backbone, or Ember) are familiar with how mvc works in UI (user interface, front end). These frameworks implement MVC, making it easier to change views as needed in a single page, and the core concepts of Model-View-Controller (mvc) are controllers that handle incoming requests, views that display information, models that represent business rules, and data access.
Therefore, when we need to create an application that needs to switch out of different content in a single page, we usually choose to use one of the above frameworks. However, if we only need a framework for view switching in a url without additional bundling, we don't have to use complex frameworks like Angular and Ember. This paper tries to use simple and effective methods to solve the same problem.
Concept
The code in the application uses the "#" in urls to realize the navigation of MVC mode. The application starts with a default url, and the hash-based code loads the application view and applies the object-model to the view template.
The url format looks like this:
Http://Domain Name/index.html#/Route Name
The view content must bind the values and properties of the object model as {{Property-Name}}. The code looks for this special template format and replaces the attribute values in the object model.
Views loaded asynchronously in ajax are placed in placeholders on the page. The view placeholder can be any element (ideally div), but it must have a special attribute based on which the code locates it, which is also helpful to the code's implementation. When the url changes, the scene is repeated and another view is loaded. That sounds easy! The following flowchart explains the message jump in this particular implementation.
Write code
We started with the basic module design pattern, and finally exposed our libs to the global scope in the form of facade design pattern.
; (function (w, d, undefined) {/ / rest of the code}) (window, document)
We need to store the view element in a variable so that it can be used multiple times.
Var _ viewElement = null; / / element that will be used to render the view
We need a default route to deal with situations where there is no routing information in the url so that the default view can be loaded instead of displaying a blank page.
Var _ defaultRoute = null
Now let's create the constructor of our main MVC object. We will store routing information in "_ routeMap"
Var jsMvc = function () {/ / mapping object for the routes this._routeMap = {};}
It is time to create a routing object in which we will store information about routes, templates, and controllers.
Var routeObj = function (c, r, t) {this.controller = c; this.route = r; this.template = t;}
Each url will have a special routing object routeObj. All of these objects will be added to the _ routeMap object so that we can get them later through key-value.
To add routing information to MVC libs, we need to expose a method in libs. So let's create a method that can be used by their 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 (contoller, route and template). They are:
Controller: the role of the controller is to access a specific route.
Route: the route of the route. This is the part that follows the # in url.
Template: this is the external html file, which is loaded as a view of this route. Now our libs needs a pointcut to parse the url and serve the associated html template page. In order to do this, we need a method.
The Initialize method does the following:
1) get the initialization of the elements related to the view. The code needs an element with the view attribute so that it can be used to look up in the HTML page:
2) set the default route
3) verify whether the view elements are reasonable
4) bind window hash change event. When different hash values of url change, the view can be updated in time.
5) *, start mvc
/ / Initialize the Mvc manager object to start functioning jsMvc.prototype.Initialize = function () {var startMvcDelegate = startMvc.bind (this); / / get the html element that will be used to render the view _ viewElement = d.querySelector (& apos; [view] & apos;); 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. This agent is called when the hash value changes. Here is the sequence of actions we do when the hash value changes:
1) get the hash value
2) get the routing value from hash
3) get the routing object routeObj from routing map object _ routeMap
4) if there is no routing information in url, you need to obtain the default routing object
5) *, invoke the controller associated with this route and provide services for the view of this view element
All the steps above are implemented by the following startMvc method
/ / function to start the mvc support function startMvc () {var pageHash = w.location.hash.replace (& apos;#', & apos;'), routeName = null, routeObj = null; routeName = pageHash.replace (& apos;/', & apos;'); / / 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 load the appropriate view asynchronously using the XML HTTP request. To do this, we pass the value of the routing object and the view element to the method loadTemplate.
/ Function to load external html data function 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 (& apos;Microsoft.XMLHTTP') } xmlhttp.onreadystatechange = function () {if (xmlhttp.readyState = = 4 & & xmlhttp.status = = 200) {loadView (routeObject, view, xmlhttp.responseText);}} xmlhttp.open (& apos;GET', routeObject.template, true); xmlhttp.send ();}
Currently, all that is left is to load the view and bind the object model to the view template. We will create an empty model object and pass the method-related model to wake up the routing 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 to prepare the model object.
The replaceToken method is used to bind the model with the HTML template
/ / Function to load the view with the template function 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 [XSS _ clean] = viewHtml } function replaceToken (viewHtml, model) {var modelProps = Object.getOwnPropertyNames (model), modelProps.forEach (function (element, index, array) {viewHtml = viewHtml.replace (& apos; {{& apos; + element + & apos;}} & apos;, model [element]);}); return viewHtml;}
*, we expose the plug-in outside the global scope of js
/ / attach the mvc object to the window w [& apos;jsMvc'] = new jsMvc ()
Now, it's time to use this MVC plug-in in our single-page application. In the next code snippet, the following are implemented:
1) introduce this code into the web page
2) add routing information and view template information with controller
3) create controller function
4) *, initialize lib.
In addition to the links we need above to navigate to different paths, the view properties of a container element contain the view template html.
JavaScript Mvc .NavLinkContainer {padding:5px; background-color: lightyellow;} .NavLink {background-color:black; color: white; font-weight:800; text-decoration:none; padding:5px Border-radius:4px;} .NavLink: hover {background-color:gray;} Navigation Links Home Contact Admin View jsMvc.AddRoute (HomeController, & apos;home', & apos Views/home.html'); jsMvc.AddRoute (ContactController, & apos;contact', & apos;Views/contact.html'); jsMvc.AddRoute (AdminController, & apos;admin', & apos;Views/admin.html'); jsMvc.Initialize (); function HomeController (model) {model.Message = & apos;Hello World&apos } function ContactController (model) {model.FirstName = "John"; model.LastName = "Doe"; model.Phone = & apos;555-123456 model.Phone;} function AdminController (model) {model.UserName = "John"; model.Password = "MyPassword";}
The above code has a section that contains a conditional comment for IE.
If the version of IE is less than 9, then the function.bind,Object.getOwnPropertyNames and Array.forEach attributes will not be supported. So we need to feedback whether the code supports it by determining whether the browser is lower than IE9.
The contents include home.html, contact.html and admin.html. Please see below:
Home.html:
{{Message}}
Contact.html:
{{FirstName}} {{LastName}} {{Phone}}
Admin.html:
User Name Password
The complete code is available from the given download link.
How to run the code
It's easy to run this code, and you need to create a Web application on your favorite Web server. Here's an example of IIS.
First of all, add a Web application to the default site.
Then set the required information: alias, physical path, application pool, user authentication information, and click OK.
* navigate to the content directory of the Web application and browse the HTML page you want to open.
Running on the server is necessary because the code is loaded from the view stored in an external file, and the browser will not allow our code to execute in a non-hosted server environment. Of course, if you use Visual Studio, then right-click on the target html file and select 'View In Browser'.
Browser support
This code is supported by most modern browsers. For IE8 and below browsers, there is a separate code to support it, but unfortunately, this code is much more than 100 lines. So the code is not 100% cross-browser compatible, so you need to fine-tune the code when you decide to use it in the project.
On how to use the code to achieve the JavaScript MVC style framework to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.