How to use JS to realize the idea of dependency injection, the back-end frame idea moved to the front to _javascript skills

Source: Internet
Author: User
Tags object object tagname hasownproperty

When we are doing some pages, many of them are implemented with Ajax, in the display when there are many forms submitted add or update operation, obviously so annoying, suddenly thought of a better method, below to share with you how to use JS to rely on injection of thought, the back-end frame ideas to move to the front.

Application scenario: One by one correspondence between front and back, form content save, list statement, etc.

Architecture idea: Distributor, Dependency injection, etc.

Basic code statement:

J.extend ({Dispatcher: (function () {var _route = {},//default Module _module = {//Authorization 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 (_modul E, 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-C
   Ontainer '), Searchform: $ (' #form-post '), SearchButton: $ (' #search-button '),   Post: {}}, config.list);
  }) ()} return _tmp_route; return {ajax:new _container (), Intercept: {module:function (module) {$.extend (True, _module, Modul
    e);
      }, 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.validation.init (config.validation); Config.validation.fireTarget.on (' click ', function () {if (!_module.validation | |!config.validation.formtarge
            T.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.fire
            Target} ajax_data = $.extend (Ajax_data, config.post);
            _ajax.call (Ajax_data);
           return false; })} if (config.list) {if (!$.fn.pagination) {throw new Error (' J.dispatcher.i Ntercept.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 global = {datatransform: {"Default": function () {if (t) Ypeof (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" && Object.prototype.toString.call (AR Guments[0]). toLowerCase () = = "[Object Object]" &&!arguments[0].length) {return {data:j.json.tostring (argum
   Ents[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 6-20 password suggestions are 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 (value);
  }, "4-32-bit characters." Support Chinese characters, letters, numbers, "-\" \ "_\" combinations); 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 && pa
    Rms[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 '))!conf Ig.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 ') t
   Hrow 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 () {}, Saveprofi Le:function () {}, Getlist:function () {}}, partnership: {signup:function () {}, Getlist:function ()
 {}}, Venue: {getlist: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 ', ' Enable ', ' operation '], R Owfield: [' AccountCode ', ' accountname ', ' accounttype ', ' companytype ', ' registertime ', ' lastactivitytime ', ' IsAvailable ', function (item) {var html = ' <a href= '/account/sub?type=edit&id= ' + item. Id + ' "class=" K-table-icon fa-edit mr15 "title=" edit Info "></a> ' + ' <a href=" javascript:; "class=" k-table-i Con 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=" has "></a>" enabled; else return ' <a href= ' javascript:; "onclick=" Operate (this,\ ' set\ ', {id: \ ' + data.) Id + ' \ ', isenable:1}) "class=" K-table-icon c-error glyphicon glyphicon-ban-circle "title=" has 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/detail?accountname= ' + encodeuricomponent (this.
  AccountName);
 }
 }
})

Effect Chart:


For example, the contents of a form are saved, which is much 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 ()); Coded data
}
}
}
Rules. 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:function (Messages) {
Messages. Name.remote = ' The company has been registered! ';
Messages. Accountname.remote = ' The username already exists! ';
Messages. Confirmparssword.equalto = ' two times password inconsistency ';
},
Filters: [' Cellphone ', ' Email ']
},
Post: {
Success:function () {
alert (this.message);
window.location = '/company/list ';
}
}
});
Back end: The back end is actually very simple class, as long as there is such a distributor of the implementation address can be, such as the above:/company/save

PS: Front-End management Framework I am a background framework for bootsrap based.

Some students asked, JS what what, this is only their own encapsulation of a JS library, follow-up will share with you

The above content is the whole narration of this article, hope to be helpful to everybody.

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.