How to Use js to implement the idea of dependency injection and move the idea of backend framework to the frontend _ javascript skills

Source: Internet
Author: User
Tags hasownproperty
This article mainly introduces the idea of implementing dependency injection in js. The idea of backend framework is moved to the front end. If you need it, you can refer to the idea that many pages are implemented using ajax, there are a lot of add or update operations submitted by forms during display. Obviously this is very annoying. I suddenly came up with a better method. Next I will share with you the idea of how to implement dependency Injection Using js, the backend framework idea is moved to the front end.

Application scenarios: one-to-one correspondence between front and back ends, saving form content, and listing statements.

Architecture: distributor and dependency injection.

Basic code statement:

J. extend ({dispatcher: (function () {var _ route = {}, // default module _ module = {// authorize authenticate: true, // verify validation: true, // data conversion dataTransform: true,}, _ state = {error: function () {}}, _ ajax = function () {j. ajax (this)}; function _ container () {// initializer. return _ route;} function _ configuration (config, _ tmp_route) {if (config) {config. module & (_ module = $. extend (_ mod Ule, config. module) config. state & (_ state = $. extend (_ state, config. state) config. post & config. post. queryString & (function () {if (! /^ \? /. Test (config. post. queryString) {_ tmp_route + = "? ";} _ Tmp_route + = config. post. queryString;}) () config. list & (function () {config. list = $. extend ({pageSize: 15, wrapped: $ ('# list-iner'), searchForm: $ ('# form-post'), searchButton: $ ('# search-button'), post :{}}, config. list) ;}) ()} return _ tmp_route;} return {ajax: new _ container (), intercept: {module: function (module) {$. extend (true, _ module, module) ;}, route: function (route) {If (! $. IsEmptyObject (_ route) return; $. extend (true, _ route, route); for (var I in _ route) {if (_ route. hasOwnProperty (I) {var _ controller = _ route [I]; for (var k in _ controller) {if (_ controller. hasOwnProperty (k) & j. utils. isFunction (_ controller [k]) {(function () {var clone = j. clone (_ controller [k]), _ tmp_route = '/' + I + "/" + k; _ controller [k] = function (config) {var url = _ configuration (co Nfig, _ tmp_route); if (j. utils. isFunction (clone) {clone. apply (_ module, config);} // todo modules if (! (_ Module. authenticate & j. utils. isFunction (_ module. authenticate) & _ module. authenticate () | _ module. authenticate === true) {console. log ('J. ajax. '+ I + ". "+ k +" authenticate failed. "); config. state. error (); return false;} if (config. validation) {_ module. validation. init (config. validation); config. validation. fireTarget. on ('click', function () {if (! _ Module. validation |! Config. validation. formTarget. valid () return false; var data = _ module. dataTransform (! Config. post. data? Config. validation. formTarget. serializeJson (): config. post. data) var ajax_data = {url: url, data: data, fireTarget: config. validation. fireTarget} ajax_data = $. extend (ajax_data, config. post); _ ajax. call (ajax_data); return false ;}} if (config. list) {if (! $. Fn. pagination) {throw new Error ('J. dispatcher. intercept. list need jQuery. pagination, please load jQuery. pagination before this file. ')} config. list. onChange = function (pageIndex) {var $ this = this; this. showLoading (); var formData = config. list. searchForm. serializeJson (); formData. pageIndex = pageIndex; formData. pageSize = $ this. pageSize; var data = _ module. dataTransform (! Config. list. post. data? FormData: config. list. post. data) var ajax_data = {url: url, data: data,} $. extend (true, ajax_data, config. list. post); ajax_data.success = function () {$ this. generateData (this. totalRecords, this. list);} j. jsonp (ajax_data)} j. list. table (config. list); config. list. searchButton. on ('click', function () {config. list. wrapped. empty (); j. list. table (config. list);}) }}} () }}}}}) ()}) var gl Obal = {dataTransform: {"default": function () {if (typeof (arguments [0]) = "object" & Object. prototype. toString. call (arguments [0]). toLowerCase () = "[object]" &! Arguments [0]. length) {return j. json. toKeyValString (arguments [0], true);} else if (j. utils. isString (arguments [0]) {return arguments [0] ;}else {return {}}, "objectData": function () {if (typeof (arguments [0]) = "object" & Object. prototype. toString. call (arguments [0]). toLowerCase () = "[object]" &! Arguments [0]. length) {return {data: j. json. toString (arguments [0])} else if (j. utils. isString (arguments [0]) {return arguments [0];} else {return {};}} j. dispatcher. intercept. module ({authenticate: function () {}, validation: (function () {var hasCongfig = false; function _ config () {if (! $. Fn. validate) {throw new Error ('J. dispatcher. intercept. module. validation need jQuery. validate, please load jQuery. validate before this file. ')} jQuery. validator. addMethod ("isPassword", function (value, element) {return j. config. reg_phone.test (value) ;}, "Please enter a 6-20 password. It is recommended that it consist of numbers, letters, and symbols! "); JQuery. validator. addMethod ("isMobile", function (value, element) {return j. config. reg_phone.test (value) ;}, "Please enter your mobile phone number correctly"); jQuery. validator. addMethod ("isEamil", function (value, element) {return j. config. reg_email.test (value) ;}, "enter the correct email address"); jQuery. validator. addMethod ("isUserName", function (value, element) {return j. config. reg_login_name.test (value) ;}, "4-32 characters. supports Chinese characters, letters, numbers \ "-\" \ "_ \" Combination ") ;} Function _ getRequired (parms, filters) {if (parms instanceof jQuery & parms. length> 0 & parms [0]. tagName = 'form') {var config = {}; parms. find ('[name]'). each (function () {if (! Filters | filters. indexOf (this. name) =-1) {config [this. name] = {required: true };}) return config;} else {for (var I in parms) {if (parms [I]) {parms [I] ['required'] = true;} else {parms [I] = {required: true }}} return parms ;}} function _ getMessage (parms, filters) {if (parms instanceof jQuery & parms. length> 0 & parms [0]. tagName = 'form') {var config = {}; parms. find ('[name] '). Each (function () {if (! Filters | filters. indexOf (this. name) =-1) {config [this. name] = {required: $ (this ). attr ("data-required-message") };}) return config ;}} function _ init (config) {if (! HasCongfig) {hasCongfig = true; _ config ();}! Config. formTarget & $ ('# form-post'). length> 0 & (config. formTarget = $ (' # form-post '))! Config. fireTarget & $ ('# post-button'). length> 0 & (config. fireTarget = $ ('# post-button') if (! (Config. fireTarget & config. fireTarget instanceof jQuery & config. fireTarget [0]. type. toUpperCase () = 'submit ') throw new Error ("j. validator. init needs config. submitTarget param, its type is submit "); if (! (Config. formTarget & config. formTarget instanceof jQuery & config. formTarget [0]. tagName = 'form') throw new Error ("j. validator. init needs config. formTarget param, its type is form "); var rules = _ getRequired (config. formTarget, config. filters), messages = _ getMessage (config. formTarget, config. filters); config. rulesCallBack & config. rulesCallBack (rules); config. messagesCallBack & config. messagesCallBack (messages); config. formTarget. validate ({debug: true, rules: rules, messages: messages});} return {init: function (config) {_ init (config) ;}, validate: function () {return config. formTarget. valid () ;}}) (), dataTransform: global. dataTransform. objectData}) j. dispatcher. intercept. route ({passport: {signin: function () {this. dataTransform = global. dataTransform. default ;}, signout: function () {}, reg: function () {}, cpwd: function () {this. dataTransform = global. dataTransform. default ;}}, company: {save: function () {}, getList: function () {}}, account: {save: function () {}, saveProfile: function () {}, getList: function () {}}, partnership: {signup: function () {}, getList: function () {}}, venue: {getList: function () {save: function () {},}, show: {save: function (){},}});

For example, use list:

J. dispatcher. ajax. account. getList ({list: {header: ['number', 'username', 'account type', 'Company type', 'registration time', 'last logon time ', 'Enable ', 'operation'], rowField: ['accountcode', 'accountname', 'accounttype', 'companytype', 'registertime', 'lastactivitytime ', 'isavailable', function (item) {var html = ''+''; return html;}], formatColumn: function (item, data) {if (item. isAvailable! = Undefined) {if (item. isAvailable = true) {return '';} else if (item. lastActivityTime) {var now = moment (item. lastActivityTime); return now. format ('yyyy-MM-DD HH: mm: ss');} else if (item. registerTime) {var now = moment (item. registerTime); return now. format ('yyyy-MM-DD HH: mm: ss') ;}}, rowClick: function () {window. location = '/account/detail? AccountName = '+ encodeURIComponent (this. AccountName );}}})

:


For example, it is easier to save the form content:

J. dispatcher. ajax. company. save ({
Validation :{
RulesCallBack: function (rules ){
Rules. Name. remote = {
Url: '/handler/validation. ashx? Type = cn ',
Type: "post", // submission method
Data :{
CompanyName: function (){
Return encodeURIComponent ($ ("# Name"). val (); // encode the data
}
}
}
Rules. ConfirmParssword. Failed to = "# Password ";
Rules. AccountName. remote = {
Url: '/handler/validation. ashx? Type = ',
Type: "post", // submission method
Data :{
AccountName: function (){
Return encodeURIComponent ($ ("# AccountName"). val (); // encode the data
}
}
}
},
MessagesCallBack: function (messages ){
Messages. Name. remote = 'this company has been registered! ';
Messages. AccountName. remote = 'this user name already exists! ';
Messages. ConfirmParssword. Conflict to = 'inconsistent passwords ';
},
Filters: ['Cellphone', 'email ']
},
Post :{
Success: function (){
Alert (this. message );
Window. location = '/company/list ';
}
}
});
Backend: the backend is actually a very simple class, as long as there is such an implementation address of the distributor, such as the above:/company/save

PS: front-end management framework I am a background framework based on boot13c.

Some people asked, What is js? This is just a self-encapsulated js library and will be shared with you later.

The above content is all described in this article and I hope to help you.

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.