JS implementation of the idea of dependency injection, back-end framework ideas moved to the front-end to

Source: Internet
Author: User
Tags tagname hasownproperty

The foregoing: When we write some pages, many need to use Ajax to achieve, show a lot of forms submitted by the Add or update operation, too annoying, can there be any method can be simpler? To be honest, I was forced by the company.

Application scenario: Back and forth one by one correspondence, form content preservation, list statement, etc.

Architectural Ideas: Distributors, Dependency injection, and so on.

Basic code statement:

J.extend ({Dispatcher: (function () {var _route = {},//default Module_module = {//authorization authe Nticate:true,//verify Validation:true,//Data Conversion datatransform:true,},_state = {Err                  Or:function () {}}, _ajax = function () {J.ajax (this)};            function _container () {//initializer.        return _route; } function _configuration (config, _tmp_route) {if (config) {Config.module && (_ module = $.extend (_module, Config.module)) config.state && (_state = $.extend (_state, config.state) ) Config.post && config.post.queryString && (function () {if (!/^\?/.te                    St (config.post.queryString)) {_tmp_route + = "?";                } _tmp_route + = config.post.queryString; }) () Config.list && (function () {config.list = $.extend ({pagesize:15, wrap PED: $ (' #list-container '), Searchform: $ (' #form-post '), SearchButton: $ (' #se                Arch-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 (config, _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.valid                                            Ation.init (config.validation); Config.validation.fireTarget.on (' click ', function () {if (!_module.validat Ion | |                                                !config.validation.formtarget.valid ()) return false; var data = _module.datatransform (!config.post.data? Config.validation.formTarget.serializeJ Son (): Config.post.data) v                                       Ar 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.dispatche                                            R.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.empt                                                Y ();                                            J.list.table (config.list);                                })                                        }                                    }                                    }())                }                            }                        }                    } }}}) var global = {datatransform: {"Default": function () {if (typeof (Arguments[0]) = = "Object" && Object.prototype.toString.call (Arguments[0]). toLowerCase () = = "[Object 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" && OBJ                Ect.prototype.toString.call (Arguments[0]). toLowerCase () = = "[Object 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.valida tion need jquery.validate,please loadJquery.validate before this file. ') } jQuery.validator.addMethod ("Ispassword", function (value, Element) {return J.config.reg_phone            . Test (value); }, "Please enter 6-20 password suggestions made up of numbers, letters and symbols!"            ");            JQuery.validator.addMethod ("IsMobile", function (value, Element) {return j.config.reg_phone.test (value);            }, "Please fill in your mobile phone number correctly");            JQuery.validator.addMethod ("Iseamil", function (value, Element) {return j.config.reg_email.test (value);            }, "Please fill in the correct email address"); JQuery.validator.addMethod ("Isusername", function (value, Element) {return j.config.reg_login_name.test (VA            Lue);        }, "4-32-bit character. Support Chinese characters, letters, numbers \"-\ "\" _\ "combination"); } function _getrequired (parms, filters) {if (parms instanceof jQuery && parms.length > 0 &am                p;& 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 &G T                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: {get List:function () {save:function () {},}, show: {Save:function () {},}});

Such as list use:

J.dispatcher.ajax.account.getlist ({list: {header: [' Number ', ' username ', ' account type ', ' Company type ', ' Registration Time ') , ' Last login time ', ' whether enabled ', ' Operation ', Rowfield: [' AccountCode ', ' accountname ', ' accounttype ', ' companytype ', ' Regi ' Stertime ', ' lastactivitytime ', ' isavailable ', function (item) {var html = ' <a href= '/account/s Ub?type=edit&id= ' + item. Id + ' "class=" K-table-icon fa-edit mr15 "title=" Edit info ></a> ' + ' <a href= ' Java Script: "class=" K-table-icon fa-trash "title=" Delete account "onclick=" Operate (this,\ ' delete\ ', {id: \ ' + item.)                        Id + ' \ '}) ' ></a> ';                    return HTML; }], Formatcolumn:function (item, data) {if (item. IsAvailable! = undefined) {if (item. IsAvailable = = true) {return ' <a href= ' javascript:; ' onclick= ' Operate (this,\ ' SET\ ', {id: \ ' + data.                            Id + ' \ ', isenable:0}) "class=" K-table-icon glyphicon glyphicon-ok-circle "title=" Enabled "></a>"; } else return ' <a href= ' javascript:; ' onclick= ' ope Rate (this,\ ' set\ ', {id: \ ' + data.                        Id + ' \ ', isenable:1}) "class=" K-table-icon c-error glyphicon glyphicon-ban-circle "title=" Disabled "></a>"; } 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/deta Il?accountName= ' + encodeuricomponent (this.                    AccountName); }                }            })

For example, if the form content is saved, it will be simpler:

 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 ()); Encoded data}}} rule                        S.confirmparssword.equalto = "#Password"; Rules. accountname.remote = {url: '/handler/validation.ashx?type=an ', type                                    : "POST",//Submission method data: {accountname:function () { Return encodeURIComponent ($ ("#AccountName"). Val ());                              Coded data   }}}, Messagescallback:func tion (Messages) {messages. Name.remote = ' The company has been registered!                        ‘; Messages. Accountname.remote = ' The user name already exists!                        ‘; Messages.                    Confirmparssword.equalto = ' two times password inconsistent ';                                        }, Filters: [' Cellphone ', ' Email '}, Post: {                        Success:function () {alert (this.message);                    window.location = '/company/list '; }                }            });

  

Backend: The backend is actually very simple class, as long as there is such a distributor implementation address can be, such as the above:/company/save

PS: Front-end management framework I am a background frame based on bootsrap, can see the Apprentice Help Demo page: http://www.xuetub.com/plugin/jquery/278

A classmate asked, J What, this is just a JS library of their own package, follow-up will share with you

Communication: Too busy, to code statements mainly, many details are not optimized, heroes can optimize their own, such as small white, small black, small yellow classmate, can pay attention to the Apprentice help, www.xuetub.com, focus on jquery plug-ins, see the demo, sweep two-dimensional code attention to me.

JS implementation of the idea of dependency injection, back-end framework ideas moved to the front-end to

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.