Home  >  Article  >  Web Front-end  >  Template method singleton in javascript

Template method singleton in javascript

小云云
小云云Original
2018-01-15 13:54:461066browse

This article mainly introduces the relevant information about the implementation method of template method singleton in JavaScript. I hope this article can help everyone. Friends in need can refer to it. I hope it can help everyone.

Implementation method of template method singleton in javascript

Template method singleton

Definition of template method: parent class Define a set of operating algorithm skeletons and extend some implementation steps to subclasses, so that subclasses can redefine some implementation steps in the algorithm without changing the algorithm structure of the parent class.

Code block

html part, for example:


js part, for example:


  //格式化字符串方法
  function fromateString(str, data) {
   return str.replace(/\{#(\w+)#\}/g, function(match, key){
    return typeof data[key] === undefined ? '' : data[key]
   });
  }
  //基础导航
  var Nav = function (data) {
   //基础导航样式模板
   this.item = '{#name#}';
   //创建字符串
   this.html='';
   for (var i = 0; i < data.length; i++) {
    this.html += fromateString(this.item, data[i]);
   }
   return this.html;
  }
  //带有信息提示信息导航
  var NumNav = function (data) {
   //消息提醒小心组件模板
   var tpl = '

{#num#}

'; for (var i = data.length -1; i >= 0; i--) { data[i].name += data[i].name + fromateString(tpl, data[i]); } return Nav.call(this, data); } //带有链接地址的导航 var LinkNav = function (data) { //消息提醒小心组件模板 var tpl = '{#link#}'; for (var i = data.length -1; i >= 0; i--) { data[i].name += data[i].name + fromateString(tpl, data[i]); } return Nav.call(this, data); } //测试带有信息提示的导航 var nav = document.getElementById('content'); nav.innerHTML = NumNav([ { href : 'www.baidu.com', title : '百度一下你就知道', name : '百度', num : 10, link : 'www.baidu.com' }, { href : 'www.taobao.com', title : '淘宝商城', name : '淘宝', num : 2, link : 'www.taobao.com' }, { href : 'www.qq.com', title : '腾讯首页', name : '腾讯', num : 3, link : 'www.qq.com' } ]);

In fact, the template method pattern is not only used when we normalize components, but is also commonly used when creating pages. The above code can derive the encapsulation of static pages and the interactive encapsulation of business logic.

Related recommendations:

Code examples on the definition and usage of template method patterns in Java classic design patterns

PHP template method pattern example code sharing

Template method pattern and its PHP implementation

The above is the detailed content of Template method singleton in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn