Skip to content

四火的唠叨

一个纯正程序员的啰嗦

Menu
  • 所有文章
  • About Me
  • 关于四火
  • 旅行映像
  • 独立游戏
  • 资源链接
Menu

A page widgetization practice

Posted on 02/16/201506/23/2019 by 四火

widget

I was working on the page reconstruction recently, and here is how I divide a page into widgets and how do they interacts in this new attempt.

Core Concepts

Page and widget: A page is composed by several widgets, and a widget is the minimum unit for reuse.

Widget controller: Accepts multiple widget data requirements and deduplicates their data types, sends Ajax request to server side, receives bound data of different types in JSON format, and deliver to each widget to render. It works as the core for page aggregation. The reason a centralized controller on the page sends request to server side rather than widgets do themselves is to reduce the Ajax request count and improve b/s interaction efficiency.

Data type, data format and data: A widget defines a way of data visualization, which requires the data in one certain data format, but in different data types. Say, a 2-dimension chart widget visualizes the data in the format of 2-d number array. Data type is a business aware concept, meaning what the data stand for.

process

Folder structure

ICanHaz.js
jquery.js
require.js
css.js  // RequireJS plugin
text.js // RequireJS plugin
widget-controller.js
date    // widget folder, contains:
-- template.html  // widget template
-- widget.css     // widget styles
-- widget.js      // widget javascript
-- test.html      // test page
-- test.js        // test page javascript
-- test.json      // test page data

The widget named “date” is self-contained, specifically with its test cases included. Simple, decoupled and reusable, the whole mechanism is composed by:

controller / widget / widget styles / widget template / widget test suite

Code

The code of the controller (widget-controller.js):

/**
 * Core controller for widget aggregation.
 */
define([],
    function() {
        return function(){
            // key: data type, value: widget
            var mappings = {};
            var widgets = [];

            var preCallback = function(){};
            var postCallback = function(){};

            /**
             * add a widget to page
             * @return this
             */
            this.add = function(widget) {
                widgets.push(widget);

                if (widget.dataTypes) {
                    $.each(widget.dataTypes, function(index, dataType) {
                        if (!mappings[dataType])
                            mappings[dataType] = [];

                        mappings[dataType].push(widget);
                    });
                }
                
                return this;
            };

            /**
             * commit data and send an Ajax request, parse and deliver responded data to each widget
             * @param params page level parameters
             * @return this
             */
            this.commit = function(params) {
                // TODO, sending request to server side, deliver the result data to widgets according to mappings, and call this.render to finalize the widget visualization
                return this;
            };

            /**
             * render widget with data, exposing this method for easier local test
             * @param widget
             * @param data
             * @return this
             */
            this.render = function(widget, data) {
                widget.render.call(widget, data);
                return this;
            };

            /**
             * set page level callback when data retrieved, but before any widget rendering:
             * function(data) {} // returned value will be treated as the data updated for rendering
             * @param func
             * @return this
             */
            this.setPreCallback = function(func) {
                preCallback = func;
                return this;
            };

            /**
             * set page level post callback after the rendering of all widgets, specifically for customized interactions between widgets:
             * function(data) {}
             * @param func
             * @return this
             */
            this.setPostCallback = function(func) {
                postCallback = func;
                return this;
            };
        };
    }
);

Test page (test.html) is the entrance for local test. Considering the legacy code, I didn’t import JQuery and ICanHaz by RequireJS:

<html>
<head>
	<script type="text/javascript" src="../jquery.js"></script>
	<script type="text/javascript" src="../ICanHaz.js"></script>
	
	<script data-main="test" src="../require.js"></script>
</head>
<body>
	<div>
		<widget name="birth-date" />
	</div>
	<div>
		<widget name="death-date" />
	</div>
</body>
</html>

Please note the local test can only be run on FireFox or Chrome because of this limitation.

Javascript for test page (test.js). Two instances (birthDateWidget and deathDateWidget) of the same widget date:

require.config({
    baseUrl: '../',
    paths: {
        'jquery' : 'jquery',
        'icanhaz' : 'ICanHaz',
        'text' : 'text',
        'css' : 'css',
        'domReady' : 'domReady',

        'widget-controller' : 'widget-controller',
        'widget-date' : 'date/widget'
    }
});

require(['widget-controller', 'widget-date', 'text!date/test.json'], function (WidgetController, DateWidget, json){
    var controller = new WidgetController();

    var birthDateWidget = new DateWidget({name : 'birth-date'});
    var deathDateWidget = new DateWidget({name : 'death-date'});
    
    controller.add(birthDateWidget).add(deathDateWidget);
    //controller.commit({...}); sending ajax request

    var dataObj = eval ("(" + json + ")");
    controller.render(birthDateWidget, dataObj.birth).render(deathDateWidget, dataObj.death);
});

Widget javascript (widget.js) loads its styles and visualize the data to actual DOMs:

define(['text!date/template.html', 'css!date/widget'],
    function(template) {
        ich.addTemplate('widget-date-template', template);
        
        return function(attrs){
            this.render = function(data){
                var html = ich['widget-date-template'](data);
                $("widget[name=" + attrs.name + "]").replaceWith(html);
            };
        };
    }
);

Widget styles (widget.css) are only be imported when the widget is actually used on the page:

div .widget-date {
	margin-top: 10px;
	border: 1px solid #000000;
}

ICanHaz is used to decouple data and widget template, and the two are finally aggregated on a widget.

Widget template (template.html):

<div class="widget-date">
	type: {{name}}, date: {{date}}
</div>

Data (test.json), which is hard coded for widget test, but should be retrieved from server side in reality:

{
	birth : {name: 'birth', date : '2015-02-14'},
	death : {name: 'death', date : '2015-03-14'}
}

The prototype code can be download here: prototype.zip.

====================================================================

[2/17/2015] Updated: create “template controller” to move the template logic out of widget.

Template (template-controller.js):

/**
 * Template controller.
 * @module
 */
define([],
    function() {
        /**
         * Template controller constructor.
         * @class
         * @param name, template controller name, used as the key for compiled template storage
         * @param template
         */
        return function(name, template) {
            // template should be compiled only once
            ich.addTemplate(name, template);
            
            /**
             * Render the data on widget.
             * @param attrs, widget level attributes, specifically, attrs.id should be the exactly same as the attribute id of that widget DOM
             * @param data, mutable business aware data, data has higher priority than attrs when they have the same key
             */
            this.render = function(attrs, data) {
                    // merge objects, deep copy
                    var merged = {};
                    $.extend(true, merged, attrs, data);

                    var html = ich[name](merged);
                    $("widget[name=" + attrs.id + "]").replaceWith(html);
            };
        };
    }
);

So the widget (widget.js) javascript is much simpler now:

/**
 * DateWidget module.
 * @module
 */
define(['template-controller', 'text!date/template.html', 'css!date/widget'], // template and css
    function(TemplateController, template) {
        var templateController = new TemplateController('widget-date', template);

        /**
         * Class DateWidget constructor. Method render is mandatory for any widget.
         * @class
         * @param attrs, widget level attributes, specifically, attrs.id should be the exactly same as the attribute id of that widget DOM
         * @return the concrete widget class
         */
        return function(attrs) {
            /**
             * Render the widget.
             * @param data, attrs will be merged into data and sent to template controller to finalize the rendering
             */
            this.render = function(data) {
                templateController.render(attrs, data);
            };
        };
    }
);

New code download link: widgets.zip.

文章未经特殊标明皆为本人原创,未经许可不得用于任何商业用途,转载请保持完整性并注明来源链接 《四火的唠叨》

×Scan to share with WeChat

你可能也喜欢看:

  1. 前端解耦的一个最简单示例
  2. 几道容易出错的 JavaScript 题目
  3. Backbone.js
  4. D3 介绍
  5. 从 JavaScript 的单线程执行说起

1 thought on “A page widgetization practice”

  1. IT疯狂女 says:
    02/25/2015 at 5:19 PM

    英文看不懂啊

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

订阅·联系

四火,啰嗦的程序员一枚,现居西雅图

Amazon Google Groovy Hadoop Haskell Java JavaScript LeetCode Oracle Spark 互联网 亚马逊 前端 华为 历史 同步 团队 图解笔记 基础设施 工作 工作流 工具 工程师 应用系统 异步 微博 思考 技术 数据库 曼联 测试 生活 眼界 程序员 管理 系统设计 缓存 编程范型 美股 英语 西雅图 设计 问题 面向对象 面试

分类

  • Algorithm and Data Structure (30)
  • Concurrency and Asynchronization (6)
  • System Architecture and Design (43)
  • Distributed System (18)
  • Tools Frameworks and Libs (13)
  • Storage and Data Access (8)
  • Front-end Development (33)
  • Programming Languages and Paradigms (55)
  • Testing and Quality Assurance (4)
  • Network and Communication (6)
  • Authentication and Authorization (6)
  • Automation and Operation Excellence (13)
  • Machine Learning and Artificial Intelligence (6)
  • Product Design (7)
  • Hiring and Interviews (14)
  • Project and Team Management (14)
  • Engineering Culture (17)
  • Critical Thinking (25)
  • Career Growth (57)
  • Life Experience and Thoughts (45)

推荐文章

  • 聊一聊分布式系统中的时间
  • 谈谈分布式锁
  • 常见分布式系统设计图解(汇总)
  • 系统设计中的快速估算技巧
  • 从链表存在环的问题说起
  • 技术面试中,什么样的问题才是好问题?
  • 从物理时钟到逻辑时钟
  • 近期面试观摩的一些思考
  • RSA 背后的算法
  • 谈谈 Ops(汇总 + 最终篇):工具和实践
  • 不要让业务牵着鼻子走
  • 倔强的程序员
  • 谈谈微信的信息流
  • 评审的艺术——谈谈现实中的代码评审
  • Blog 安全问题小记
  • 求第 K 个数的问题
  • 一些前端框架的比较(下)——Ember.js 和 React
  • 一些前端框架的比较(上)——GWT、AngularJS 和 Backbone.js
  • 工作流系统的设计
  • Spark 的性能调优
  • “残酷” 的事实
  • 七年工作,几个故事
  • 从 Java 和 JavaScript 来学习 Haskell 和 Groovy(汇总)
  • 一道随机数题目的求解
  • 层次
  • Dynamo 的实现技术和去中心化
  • 也谈谈全栈工程师
  • 多重继承的演变
  • 编程范型:工具的选择
  • GWT 初体验
  • java.util.concurrent 并发包诸类概览
  • 从 DCL 的对象安全发布谈起
  • 不同团队的困惑
  • 不适合 Hadoop 解决的问题
  • 留心那些潜在的系统设计问题
  • 再谈大楼扔鸡蛋的问题
  • 几种华丽无比的开发方式
  • 我眼中的工程师文化
  • 观点的碰撞
  • 谈谈盗版软件问题
  • 对几个软件开发传统观点的质疑和反驳
  • MVC 框架的映射和解耦
  • 编程的未来
  • DAO 的演进
  • 致那些自嘲码农的苦逼程序员
  • Java 多线程发展简史
  • 珍爱生命,远离微博
  • 网站性能优化的三重境界
  • OSCache 框架源码解析
  • “ 你不适合做程序员”
  • 画圆画方的故事

近期评论

  • Ticket: TRANSACTION 1.922915 BTC. Go to withdrawal >> https://yandex.com/poll/enter/BXidu5Ewa8hnAFoFznqSi9?hs=20bd550f65c6e03103876b28cabc4da6& on 倔强的程序员
  • panshenlian.com on 初涉 ML Workflow 系统:Kubeflow Pipelines、Flyte 和 Metaflow
  • panzhixiang on 关于近期求职的近况和思考
  • Anonymous on 闲聊投资:亲自体验和护城河
  • 四火 on 关于近期求职的近况和思考
  • YC on 关于近期求职的近况和思考
  • mafulong on 常见分布式基础设施系统设计图解(四):分布式工作流系统
  • 四火 on 常见分布式基础设施系统设计图解(八):分布式键值存储系统
  • Anonymous on 我裸辞了
  • https://umlcn.com on 资源链接
© 2025 四火的唠叨 | Powered by Minimalist Blog WordPress Theme