大前端周刊 第11期 (本期小编:胡国伟)

Show me the code

截流(throttle)

概念理解:固定函数执行的速率。
使用场景:DOM 事件绑定,短时间内触发多次绑定事件造成性能问题,如 onresize,onscroll等,使用节流函数可确保在指定时间内只触发一次。
简单实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
let throttle = (func, wait) => {
let context, args;
let previous = 0;

return function () {
let now = +new Date();
context = this;
args = arguments;
if (now - previous > wait) {
func.apply(context, args);
previous = now;
}
};
};

防抖(debounce)

概念理解:强制一个函数在某个连续时间段内只执行一次,哪怕它本来会被调用多次。
使用场景:

  1. 表单远程搜索,键盘多次输入取最后一次输入值作为查询关键词。
  2. 下拉菜单的延时消失。

简单实现:

1
2
3
4
5
6
7
8
9
10
11
let debounce = (func, wait) => {
let timeout;
return function () {
let context = this;
let args = arguments;
clearTimeout(timeout);
timeout = setTimeout(function () {
func.apply(context, args)
}, wait);
};
};

工具和模块

推荐功能强大的HTTP抓包调试工具:Fiddler。假如有这样一个场景,线上突然出现bug,而你正在休假、手头又没有源码,但又急需你参与问题排查,怎么办?Fiddler 便是你的救🔥利器。

  1. 官网:http://www.telerik.com/fiddler
  2. 插件(官方&第三方):http://www.telerik.com/fiddler/add-ons
  3. 快速上手:十分钟学会 Fiddler
  4. 视频教程:http://www.imooc.com/learn/37
  5. 系列文章

文章推荐

  • 代码覆盖率工具 Istanbul 入门教程
    使用 Mocha 进行单元测试时,还需要了解测试的覆盖程度,这个指标就叫做”代码覆盖率”(code coverage)。这篇文章非常全面地介绍了Istanbul,让你轻松上手。深入了解:nyc

  • 深入浅出浏览器渲染原理
    对于 HTTP 协议和浏览器渲染原理都是理解容易但不好讲明白,那么为什么不采用 Node.js 来阐述呢?以实践的方式、最简单的方式来向你展示不好讲的东西,对于 Node.js 开发者和大前端开发来说都是非常实用的。

  • 剖析Vue实现原理 - 如何实现双向绑定mvvm

    1. 了解vue的双向数据绑定原理以及核心代码模块
    2. 了解如何实现双向绑定
  • 不用call和apply方法模拟实现ES5的bind方法
    这个问题是对JavaScript基本功很好的一个检测,看JavaScript掌握的怎么样以及平时有没有去深入研究一些方法的实现,简而言之,就是有没有折腾精神。

  • 通过ES6 Generator函数实现异步操作
    文章对 Generator函数实现异步进行了深入的讲解,最后使用 promise和 generator这样的模式实现异步操作,对于实现的过程进行深入细致的分析。

  • 你了解CSS设计模式吗?
    简单来了解下CSS设计模式:

    1. BEM全称(block、element、modifier)是Yandex 团队提出的CSS Class命名法
    2. OOCSS全称(Object Oriented CSS)由Nicole Sullivan提出的css理论
    3. SMACSS是Jonathan Snook的一个CSS框架
    4. Atomic Design,原子设计
  • 我接触过的前端数据结构与算法
    作者总结了前端常常碰到的算法,主要涉及递归、节流、数组去重、栈和堆、图像处理等。代码示例较为清晰,对于初学者还是很有帮助的,比较赞同作者的观点:算法的目的是用最小的时间和最小的空间解决问题。但是有时候不用太拘泥于一定要最优的答案,能够合适地解决问题就是好方法,而且对于不同的应用场景可能要采取不同的策略。
  • JavaScript 中 4 种常见的内存泄露陷阱
    虽然Javascript有内存自动回收机制,但这并不以为着js开发使完全不用关心内存管理。文中详细介绍了什么是内存泄漏和js中容易引起内存泄漏的点,并提供了使用Chrome分析内存的方法。

招聘

TalkingData DTU 可视化团队招聘:

  • 资深前端工程师
  • 前端实习生

简历投递:

1
2
const email = 'xiang.wang#tendcloud.com'.replace('#', '@');
console.log(email);

大前端周刊 第10期 (本期小编:王祥)

Show me the code

ES 6 中引入了很多让代码看起来更简洁的新特性,比如展开运算符 (spread operator)。下面的三段代码,展示了 ES6 更简洁的对象拷贝、数组复制和可变参数的写法。

  • 对象拷贝
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// very bad
const original = { a: 1, b: 2 };
const copy = Object.assign(original, { c: 3 }); // this mutates `original` ಠ_ಠ
delete copy.a; // so does this

// bad
const original = { a: 1, b: 2 };
const copy = Object.assign({}, original, { c: 3 }); // copy => { a: 1, b: 2, c: 3 }

// good
const original = { a: 1, b: 2 };
const copy = { ...original, c: 3 }; // copy => { a: 1, b: 2, c: 3 }

const { a, ...noA } = copy; // noA => { b: 2, c: 3 }
  • 数组复制 (copy arrays)
1
2
3
4
5
6
7
8
9
10
11
// bad
const len = items.length;
const itemsCopy = [];
let i;

for (i = 0; i < len; i += 1) {
itemsCopy[i] = items[i];
}

// good
const itemsCopy = [...items];
  • 可变函数 (variadic function)
1
2
3
4
5
6
7
8
9
10
11
12
13
// bad
const x = [1, 2, 3, 4, 5];
console.log.apply(console, x);

// good
const x = [1, 2, 3, 4, 5];
console.log(...x);

// bad
new (Function.prototype.bind.apply(Date, [null, 2016, 8, 5]));

// good
new Date(...[2016, 8, 5]);

工具和模块

推荐一个 Markdown 生成 Word 文档工具 pandoc。

  1. 使用 pandoc 将 Markdown 文件转换为 Word 文档。

    1
    $ pandoc -f markdown -t docx front-end-engineering-practice.md -o mydoc.docx
  2. 安装 pandoc ( Mac )

    1
    $ brew install pandoc

文章推荐

虽然,大多数 JavaScript 机器学习库都是“新轮子”,有的甚至还在研发中,但并不会影响你的使用。在这篇文章中,我们将与你分享这些库,以及一些很酷的 AI Web 应用程序实例,帮助你开启机器学习之旅。

前端工程师也需要了解HTTP方面的一些知识,本篇文章用通俗易懂的方式讲解了平时经常听到的三次握手和四次分手究竟是什么。

Mocha 是目前最流行的测试框架之一,支持浏览器端和 Node 端的单元测试。这篇文章非常全面地介绍如何使用Mocha,让你轻松上手。

本文是阿里某前端团队,在探索一套基于NodeJS的前后端分离方案的过程中,对于前后端分离的一些认识以及思考。

在PC Web端开发的时候,我们能很方便的从浏览器开发者工具里进行网络接口调试。
在移动端开发是面对这样的需求,我们可以通过抓包工具来解决这个问题。
在Mac系统常用的抓包工具是Charles,Windows系统中常用的抓包工具是Fiddler。
下面的文章分别对Charles和Fiddler进行介绍,并图文显示了使用方法。

由易到难介绍小程序开发的流程,讲解比较层次化,比较细致,可以让人很快进行上手开发

深度的剖析了错误信息和追溯栈,从错误捕获、剖析追溯栈、不同浏览器对于追溯栈格式上的差异等等,讲解相当详细也很透彻。

关于闭包的解释有很多,很多只是从“行”上去解读,理解 JavaScript 闭包绕不开一个问题:闭包是如何实现变量保留在内存中呢?这涉及到浏览器对内存的分配与回收,本文从这个点展开图文详实的解读。拓展阅读:可视化分析js的内存分配与回收

一步一步实现一个完整的、能通过所有Test case的Promise类。文章由构造简单的promise对象开始,逐步完善逻辑。抛出问题,介绍思路,给出代码示例,比较清晰合理。自己实现已有的轮子,对于编码能力提升还是很有帮助的。

招聘

TalkingData DTU 可视化团队招聘:

  • 资深前端工程师
  • 前端实习生

简历投递:

1
2
const email = 'xiang.wang#tendcloud.com'.replace('#', '@');
console.log(email);

大前端周刊 第9期 (本期小编:包京京)

基础

文章

  • 饿了么的 PWA 升级实践
    推荐人: 胡国伟
    饿了吗本次分享了基于 vue.js 的升级实践,踩坑跳坑的过程非常精彩。阅读完本文之余也可了解下Lavas:百度推出的基于 Vue 的 PWA 解决方案,其号称帮助开发者快速搭建 PWA 应用,解决接入 PWA 的各种问题。

  • Vuex框架原理与源码分析
    推荐人:李志伟
    文章首先抛出5个核心问题,然后介绍各模块核心流程,结合图解、代码示例更利于理解。理清store构造方法你也就大致明白Vuex的实现了。

  • 每个JavaScript开发者都该懂的Unicode
    推荐人:郭俊兵
    如果你觉得理解Unicode很难,那么是时候来面对它了!其实它没你想的那么难。让我们进入抽象概念、字符、星光平面(辅助平面)和代理对的世界。

  • Webpack 性能优化 (一)
    推荐人:陶明
    文章通过项目打包场景,介绍了 resolve.alias 即利用别名做重定向的方法,在此基础上,配合module.noParse 忽略对某些模块的解析可以进一步加快速度。

  • 分享一篇介绍JS调试技巧的文章
    推荐人:李丽娇
    据说程序员不是在改bug就是在写bug的路上,由此可见调试问题这个技能的重要性。文中介绍了多种JS的调试工具和方法,并配有GIF图演示。快GET起来吧!

  • Koa2进阶学习笔记
    推荐人:耿少真
    基于async/await实现中间体系的koa2框架将会是是node.js web开发方向大势所趋的普及框架。基于generator/yield的koa1将会逐渐被koa2替代,毕竟使用co.js来处理generator是一种过渡的方式,虽然有其特定的应用场景,但是用async/await会更加优雅地实现同步写法。

  • 前端开发持续集成/持续部署(CI/CD)实例
    推荐人:包京京
    近几年,前端项目也引入了编译,构建,单元测试等现代软件工程化的标准环节。这样大提高了前端的开发效率和业务交付能力。在项目部署阶段,我们还需要引入 CI / CD 等现代化的软件开发实践,来减少风险,自动化重复操作,节省我们的时间。本文主要分享一下如何基于 gitlab 、 jenkins 让 CI/CD 跑起来。

  • 滴滴 webapp 5.0 Vue 2.0 重构经验分享
    推荐人:张成斌
    滴滴的 webapp 是运行在微信、支付宝、手 Q 以及其它第三方渠道的打车软件。借着产品层面的功能和视觉升级,我们用 Vue 2.0 对它进行了一次技术重构;本文即是本次重构中的经验分享。

  • 前端工程化实践
    推荐人:王祥
    第一篇原创文章,总结了TalkingData DTU可视化团队,在2017年上半年的实践和尝试。内容包括git工作流、代码规范和大前端的目标确定,总结过往,才能更好的迎接未来。

大前端周刊 第8期 (本期小编:耿少真)

基础

  • 掌握Chrome开发工具
    熟悉Chrome开发工具的基本功能: DOM检查器、样式面板和JavaScript控制台和一些不太为人所知的特性

  • JS函数式编程指南
    对函数式编程的目的有一个初步认识,对一个程序之所以是函数式程序的原因有一定了解

  • HTTP协议详解
    Web服务器是基于HTTP(HyperText Transfer Protocol)协议实现的,所以要实现一个Web服务器就必须了解HTTP协议,本章主要介绍HTTP协议的相关知识,让我们对HTTP协议有个理性的认识。

资源整理

  • 编程书单
    一些 GitHub 上不错的文章或电子书列表与大家分享。不乏有不少经典,可以收起来慢慢阅览。

  • Web前端导航网站
    收录了前端开发需要的大部分网站,可以快速找到自己需要的网站

文章

  • 彻底弄懂CommonJS和AMD/CMD
    推荐人:李丽娇
    经常说的CommonJS、AMD、CMD规范具体指什么?实现原理是什么?这些规范有哪些具体实现?来看这篇文章找答案。

  • 使用Node.js实现文件流转存服务
    推荐人:李志伟
    文章介绍了基于node实现分片上传大型文件,通过灵活使用Promise和递归,实现非异步模型看起来很复杂的事情。另外文章附有较为完整的单元测试,覆盖分片的缓存与切割、上传前后的md5值。

  • API设计原则
    推荐人:胡国伟
    我们平时在编写组件或者后端接口的时候都避免不了API 设计,你的API越容易使用,那么就会有越多的人去用它。那么问题来了,怎样才能设计出优秀的 API ?本文是虽然是以C++为例, 其中设计原则和思考是具有普适性的,是关于API设计一篇难得的好文章

  • 一道JS面试题所引发的”血案”,透过现象寻本质,再从本质看现象
    推荐人:张成斌
    对this、执行环境、作用域等概念进行了系统的讲解。加深对于这些易混淆概念的理解。

  • karma+webpack搭建vue单元测试环境
    推荐人:耿少真
    karma+webpack搭建vue单元测试环境介绍了vue单元测试环境搭建及查看源文件的测试覆盖覆盖率。
    Vue单元测试case写法
    测试环境搭建完成后,在此基础上vue单元测试思路介绍和case的写法。测试框架使用jasmine。

  • 【源码拾遗】axios —— 极简封装的艺术
    推荐人:陶明
    本文通过axios 功能的使用及源码分析详细说明了axios 对于功能的实现。
    axios是基于Promise的方式封装,所以分析axios源码也是对Promise的深入学习。

  • Intro to Frontend Ops
    推荐人:包京京
    Frontend Ops是这篇文章作者自己定义的一个概念,业界应该还没有统一这种叫法,不过文章作者的意思是,随着前端项目复杂程度的增加,需要类似于DevOps的工程化能力,来进行持续发布、自动化测试等等流程(本文是英文的材料,暂无译文)。

  • Koa 框架教程
    推荐人:王祥
    本文从零开始,循序渐进,教会你如何使用 Koa 写出自己的 Web 应用。每一步都有简洁易懂的示例,希望让大家一看就懂。

  • 一行 JavaScript 代码的逆向工程
    推荐人:郭俊兵
    这一行代码会被渲染成一个矩阵效果,通过一次代码解读,享受理解它的过程。
    <pre id=p><script>n=setInterval("for(n+=7,i=k,P='p.\\n';i-=1/k;P+=P[i%2?(i%2*j-j+n/k^j)&1:2])j=k/i;p.innerHTML=P",k=64)</script>

大前端周刊 第7期 (本期小编:张成斌)

基础

文章

  • 深入理解 JavaScript 数据双向绑定
    推荐人:包京京
    首先讲解一下数据双向绑定的基本原理,介绍对比一下三大框架的不同实现方式,同时会一步步完成一个简单的mvvm示例。

  • 前端开发者指南(2017)
    推荐人:郭俊兵
    内容偏向于 WEB 技术(HTML、CSS、DOM、JavaScript)和以这些技术为根基直接构建而成的开源技术。书中引用和讨论的材料要么就是同类翘楚,要么就是解决问题的流行方案。

  • 关于 Vue App 开发的一些思考
    推荐人:张成斌
    TalkingData实习生写的一篇文章。作者回顾了自己经历三个项目的开发历程,发现了很多问题,也产生了很多思考。该文章有很多值得借鉴的地方。

  • JavaScript专题之jQuery通用遍历方法each的实现

    系列目录地址
    推荐人:陶明
    文章从each 的功能实现入手不断完善,整体实现思路清晰,对于问题及解决也有详细的代码实现与解释。这是一个系列内容涵盖防抖、节流、去重、类型判断等。

  • JavaScript 数据类型和数据结构
    推荐人:李丽娇
    作为js权威文档之一,mozilla网站除了对基础只是的介绍,还会有一些总结性的文章和使用注意事项。
    这篇文章总结性地介绍了Javascript的数据类型和数据结构,并有一些使用中的注意事项。

  • 函数式编程初探

    函数式编程入门教程
    推荐人:王祥
    推荐阮一峰老师的两篇函数式入门文章,大家可能无意识的使用函数式编程一段时间了。读这两篇文章,可以将思维里零散的函数式编码习惯系串联起来。

  • Vue 全站服务器渲染 SSR 实践
    推荐人:胡国伟
    掘金分享了vue实现SSR的实践,目前来看性能问题依然很严重,仅供大家参考。

  • Vue开发常见问题集锦
    推荐人:王俐
    附:换个思路理解Javascript中的this实际开发中会遇到的问题,主要涉及技术栈: Vue-CLI、 Element UI、 Pug(Jade)、 Less、ES6;
    1、涉及问题:ES6语法转换建议使用babel-polyfill;
    2、对于let和const的使用
    3、自定义路径别名的设置
    4、 在使用 Moment.js 遇到一些问题
    5、CSS 作用域与模块

  • 详解 Vue 2.4.0 带来的 4 个重大变化
    推荐人:李志伟
    “异步组件”让你的应用代码分离,使非必要组件在首页加载后延迟加载, 从而让用户更快的看到主页;组件内新增实现“属性继承”,使你的在每个中间组件属性定义变得相当简洁;异步组件支持webpack3,vue-loaderv13.0.0将.vue文件作为ES模块输出,这使得vue能够享受新的变量提升带来的便利;保留HTML注释,咳咳…聊胜于无。

  • 异步编程之async
    推荐人:耿少真
    对async方法的深入理解。

大前端周刊 第6期 (本期小编:郭俊兵)

基础

  • CSS 样式书写规范
    不同的规范都有各自的长处与缺陷,对待所谓的规范最好的方式不是人云亦云,拿来就用,而是应该结合实际情况及需求,取长补短,取其精华去其糟粕。

  • bfc初探
    bfc全称是块级格式化上下文(block formating context),是web可视化css渲染的一部分,它是块级盒子的布局发生,浮动互相交互的部分。

  • es6精简学习
    秉着二八原则,掌握好常用的,有用的这个可以让我们快速起飞

文章

  • 推荐一个Vuex的介绍文章
    推荐人:张成斌
    使用Vue做项目时,Vuex的使用与否和怎么使用始终是回避不了的一个问题。这篇文章或许能给你一些灵感。

  • 当我们学习 Node.js 时,我们在学习什么?
    推荐人:包京京
    大家都说学 Node.js 学 Node.js,到底是学它的什么呢?是学 JavaScript 这门语言,还是学 Node.js 的 API?还是学 Node.js 各种三方库?

  • 推荐一篇关于WebSocket 的教程
    推荐人:陶明
    文章介绍了WebSocket 的特性及与HTTP对比在服务器推送上的优势,通过一个简单的示例介绍了WebSocket 部分API。

  • 推荐一篇介绍git工作流程的文章
    推荐人:李丽娇
    git成为现在最火的代码管理工具,文中详细介绍了git在团队中的使用流程,这种思路在团队协作中很是受用。同时文中介绍了gitflow使用的方法。

  • 理解 async/await
    推荐人:耿少真
    async 函数是 Generator 函数的语法糖。使用 关键字 async 来表示,在函数内部使用 await 来表示异步。

  • http协议简介
    推荐人:郭俊兵
    大致了解下http协议相关内容,有利于了解前端开发时,调用后台接口,请求做了什么。

  • Vue2.0 源码阅读:响应式原理
    推荐人:李志伟
    文章深入Vue源码,详细地解析了响应式原理。其原理大致可总结为:当数据发生改变后,相应的 setter 函数被触发,然后执行 notify 函数通知订阅者(Watcher)去更新相关视图,也会对新的数据重新 observe,更新相关的依赖关系。

  • HTTP/2 Server Push 详解(原文)
    推荐人:胡国伟
    Server Push可以将静态资源推送给客户端,实现多路复用,是HTTP/2众多协议优化中最令人振奋的特性,它大大降低了网络延迟对性能的影响。

    翻译:
  • 深入vue2.0底层思想–模板渲染
    推荐人:王俐
    Vue 2.0 中模板渲染与 Vue 1.0的区别,1.0 中采用的 DocumentFragment (想了解可以观看这篇文章),而 2.0 中借鉴 React 的 Virtual DOM。基于 Virtual DOM,2.0 还可以支持服务端渲染(SSR),也支持 JSX 语法。

  • iView 一周年了,同时发布了 2.0 正式版
    推荐人:王祥
    一周年,两个大版本,很值得称赞的成绩!能跟梁灏这样优秀的前端生态贡献者共事,我感到非常荣幸!
    正如标题所言,2.0正式版将会是一个全新的开始,她将随着Vue社区的进步而快速迭代。
    期待vue社区和iView能有更好的发展,iView不会止于组件库,更期待iView deign、iView mobile…和更多优秀的开发者参与到开源生态的共建!

大前端周刊 第5期 (本期小编:陶明)

基础

文章

  • 五种事件驱动的API架构
    推荐人:王祥
    本文会介绍 5 种事件驱动的 API 架构:WebSockets、WebHooks、REST Hooks、Pub-Sub, 以及 Server Sent Events,并分别介绍这几种架构的基础功能、使用方式以及各自的优缺点。
    对于 Node.js 开发者来说,我们天生就在使用事件驱动的架构,业界也越来越认可事件驱动架构和异步系统的优势,了解本文介绍的 5 种事件驱动API 架构。

  • 推荐一篇Three.js入门文章
    推荐人:张成斌
    文章把学习Three.js需要掌握的基本概念和知识点讲解的很详细。并且结合代码实现了一个demo。对于Three.js有兴趣的同学,是一篇不错的入门文章。

  • 推荐一篇介绍RESTful API的文章
    推荐人:李丽娇
    介绍了RESTful API的实现思想,并从http请求方式和相应内容等方面给出详细示例。
    在项目接口设计和接口对接中可做实质性参考。

  • 读 Zepto 源码之 Event 模块
    推荐人:胡国伟
    如何自己实现事件处理,本文通过深入浅出解读 Zepto Event 模块源码,给我们提供了很好的答案。

  • 深入探究 eventloop 与浏览器渲染的时序问题
    推荐人:陶明
    文章通过对那些『延迟』执行的函数思考,深入的对event loop和task进行了拆分讲解,通过实例与图示详细讲解了整个执行渲染过程。

  • vue的Virtual Dom实现- snabbdom解密
    推荐人:李志伟
    文章通过详细的图文对照、算法代码解析讲述了虚拟dom的实现,Virtual Node作为纯数据对象,patch创建或者更新DOM树,diff算法用来比较同层级,然后通过钩子和扩展模块创建有attribute、props、eventlistener的复杂dom。

  • ES6数组的扩展(rest参数和扩展运算符)
    推荐人:耿少真
    rest参数和扩展运算符都是ES6新增的特性。
    rest参数的形式为:…变量名;扩展运算符是三个点(…)。

    rest参数:
    • rest参数用于获取函数的多余参数,这样就不需要使用arguments对象了, rest参数搭配的变量是一个数组,该变量将多余的参数放入数组中
    扩展运算符:
    • 扩展运算符可以看做是 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列
  • 程序员如何快速学习新的框架
    推荐人:郭俊兵
    前端框架丰富多彩的今天,快速学习新的框架是每个前端程序员的必备技能。

  • 4种使用webpack提升vue应用的方式
    推荐人:包京京
    本篇文章所提到的几个措施大家可能都曾经在项目里用过,但是就如作者所言:你只是在用,并不知道为什么用,本文最大的价值在于提供了系统的优化方案并解释了原因

其他

  • pell
    一个非常轻的开源WYSIWYG 编辑器
  • three.js
    three.js的Demo

5 Protocols For Event-Driven API Architectures

原文:5 Protocols For Event-Driven API Architectures

The internet is a system of communication, and as such, the relationship between client and server, as well as server to server, is one of the most oft-discussed and hotly contested concepts. event-driven architecture is a methodology of defining these relationships, and creating systems within a specific set of relationships that allow for extensive functionality.

In this piece, we’re going to discuss 5 common event-driven methods — WebSockets, WebHooks, REST Hooks, Pub-Sub, and Server Sent Events. We’ll define what they fundamentally are and do, and how API providers go about using them. Additionally, we’ll provide some pros and cons on each to make choosing a solution for your platform easy and intuitive.

What is an Event-Driven Architecture?

Event-driven architectures establish an event that can be consumed and reacted to. But what is an event?

An event is essentially any significant change from one state to another, such as the change from having no messages in your inbox to have a new message in your inbox. This state can be reacted to internally (such as when the email program in question realizes a new message has been received), externally (when a user sees a notification for a new message), or used to generate another event (for instance, the message tally increases by one).

Event-driven architectures are appealing to API developers because they function very well in asynchronous environments. By crafting APIs that trigger certain functions on new event delivery, API systems don’t have to inherently wait for synchronous delivery or real time communication. This is hugely beneficial, as eliminating the need to constantly poll endpoints frees resources from otherwise wasteful purposes, reducing both general hardware requirements and call-specific overhead.

For this reason, event-driven architectures are very, very popular, and lead to improved power, bandwidth, and co-processing than other solutions and architectures such as polling and other poll-centric derivatives.

5 Types of Event-Driven Protocols for APIs

1: WebSockets

WebSockets are an interesting event-driven solution, because, for most browsers, they’re actually baked into the application itself. Essentially, WebSocket is a protocol that provides full-duplex communication on a single TCP connection. It was standardized by the Internet Engineering Task Force as RFC 6455, and the WebSocket API in Web IDL was later standardized under the W3C banner.

While the protocol itself is meant to be used between web browsers and servers, the protocol can be used in any case where there is a client-server relationship. The protocol itself is based upon TCP, with the additional HTTP interpretation statement that is considered an “Upgrade request” to allow for interoperability.

Pros

Because WebSocket is expressly designed for browser operation, it boasts extremely low overhead for what it actually does. By establishing a full-duplex conversation using a standardized methodology, connection both to and from the two entities can take place simultaneously, resulting in lower overhead and better throughput.

Additionally, the fact that these communications take place over TCP 80/443 means that environments that traditionally block non-web based applications for security reasons can still handle this protocol, as firewalls allow communication to and from this port.

Perhaps the strongest argument for the use of WebSockets are the fact that they are standardized and natively supported by all major browsers, ranging from Microsft Edge to Opera, from Firefox to Chrome. This means that any web application that ties into it will be interactable within the vast majority of both browser-based and browser-independent gateways and applications.

Cons

WebSockets have one distinct major failing — while it might have support for HTTP-like functionality, it is not HTTP whatsoever. This has implications, especially when considering optimizing in HTTP such as caching, proxying, etc., that haven’t quite become apparent.

Because WebSockets are relatively new, having been only officially standardized in 2011, the industry is still understanding what the side effects mean. Most applications that use WebSockets are designed specifically for everything that a WebSocket is — what has yet to be seen, however, is whether or not this solution is better in the long-run than any stateless solution currently available.

There is of course the fact that, as with other architectures on this list, WebSockets create an “always on” connection during the duration of data transfer. While this is fine for many uses such as media streaming and live stream calculations, it also essentially means that, for WebSockets, there is no scalability. Ports have hardcoded limitations and bandwidth, and thus in order to “scale”, you must add additional ports to match the maximum load. In stateless systems, this is less of an issue, as requests can wait and be made in such a way as to be independent on the state of the server itself.

2: WebHooks

WebHooks are a similar concept to the WebSocket. They primarily function using custom callbacks, or code that is passed as an argument to another chunk of code and executed at a specified point in time. Essentially, a WebHook is a glorified system of “if this, then do”, allowing for users independent of the event firing to craft a custom response to that event within their own system.

The term was coined by Jeff Lindsay in 2007, and quickly became popular amongst users who wished to create automated responses to exterior behaviors. A great example of this would be a developer pushing a new item to GitHub, which causes an event. A user has a system tied into the URI of a WebHook. When the push is published, the user’s system utilizes the URI of the WebHook to integrate the push into a larger build, thereby creating a compiled component.

Pros

WebHooks function a lot like WebSockets, but they’re different in some key areas. First and foremost, WebSockets are primarily designed for browser-based communications, and while they can be used regardless in any client-server communication, they do not behave well in a server-to-server setup.

WebHooks, on the other hand, work very well in server-to-server systems due to how they operate. Because the system essentially functions as the aforementioned “if this then do”, servers can be configured to tie into pre-formed URIs at any time and execute a given function whenever that event is triggered.

Additionally, WebHooks have the unique benefit of being based upon HTTP, unlike WebSockets. This means that the system can be integrated without utilizing any new infrastructure, allowing speedy adoption and relatively simple setup.

Cons

The problem with WebHooks is that a lot of their functionality can already be placed on the arguably more powerful REST architectural approach. While adopting event-driven architecture is often a requirement of the service being built, it’s a hard sell when it can be mirrored in REST while also giving the wealth of options that REST gives to the user.

These RESTful solutions such as RestMS are essentially simply message querying services, though, and do require additional infrastructure, which may or may not be doable considering the purpose of the application.

Additionally, WebHooks can be resource intensive to both the client and the server. If the client needs to notify many servers that an event has occurred, and a server needs to listen to a great deal of clients notifying of this change, you can very quickly run into a situation where your network grows uncontrollably. While HTTP does scale quite well, this is a definite negative to consider.

However, there are also ways to build a message queuing service on top of HTTP—some RESTful examples include IronMQ and RestMS.

3: REST Hooks

Speaking of RESTful examples, REST Hooks is essentially “hooking” baked into REST itself. Defined as an initiative from Zapier, this is a subject we’ve covered before — hooks are collated to a single target URL as a subscription, which pings the resource requester when a change is noted.

This approach is a response to the practice of polling, in which a client constantly checks for changes to a resource. Under the REST Hooks paradigm, the client instead waits for a change, and reacts to it. To put it simply, this is a WebHook in REST.

Pros

REST Hooks are obviously super powerful in the correct context — being able to passively receive a resource rather than dedicating processing power to constant polling frees up a lot of the client-side cost.

Perhaps the strongest argument for REST Hooks though, is the fact that it’s so easy and intuitive to use. While WebHooks utilize HTTP and thus do not need new architecture to set up, they are also limited by the fact that they are built upon HTTP, and can thus be somewhat complex to set up properly and use effectively.

REST Hooks, though, are subscription based, and as such, are simply usable by subscribing. This makes it a very easy to use solution while providing a lot of the usability and effectiveness of more complex systems.

Cons

Of course, every solution has its negatives, and REST Hooks are no different. It could be viewed that REST Hooks actually fly in the face of what REST is — session free and stateless. REST Hooks essentially create consistent polling, it’s just moved the polling from one side to another.

Then, there’s the arguable problem that REST Hooks might be doing something that has already been solved. Some would argue that TCP already does most of what REST Hooks is trying to do, and simply layering more solutions on top of HTTP to get what TCP already does is a poor approach.

4: Pub-Sub

Pub-Sub is a slightly different approach. Referred to by its full name as publish-subscribe, the concept is where events are published to a class without knowledge of the client subscribing to the class. Basically, a user will join one or more classes, and then will receive event updates without regard or knowledge to the event publisher.

The main difference here is one of conscious choice of provider — in the other solutions noted herein, a user consciously communicates with a given server or provider and receives events as pre-determined. Under the Pub-Sub scheme, the user only specifies which class they wish to be part of and what events they are interested in receiving. From there, they receive these events when one is pushed out.

A way this is often framed in internet discussions is in the frame of a radio channel. Record companies, or publishers, issue audio to the station, which then broadcasts this audio to listeners, or subscribers. Pub-sub is the middleman radio station here — listeners don’t know who gave the station the music, nor do the companies know who the listeners are. It is this segmentation that is baked into the pattern.

When we talk about Pub-Sub, we need to keep in mind that we’re actually talking about two different things. Pub-Sub can mean the methodology and general concept in programming terms, but it can also mean specific provider solutions based upon that methodology. For instance, Google’s Cloud Pub/Sub is an implementation of the general methodology within their cloud service, and allows for asynchronous many-to-many pub-sub relationships as stated above.

Pros

A huge benefit of Pub-Sub is the fact that it’s loosely coupled, and thus is extremely scalable and flexible. The only thing the event-provider is doing is generating the content — each other step is done through a separated middleman, and so the content is easily scaled and modulated to the architecture and design of the solution.

Additionally, Pub-Sub lends itself very well to testing. A subscriber is narrowly limited to a set of events that they have requested under a class, so if a failure occurs, this natural segmentation informs the provider as to where the fault is, and which class of users is experiencing the fault.

Cons

Unfortunately, decoupling is also a huge disadvantage for this pattern. By being a middleman, Pub-Sub cannot effectively notify the provider that a message has been sent, and the listener is separated from the event and thus may not know if a message wasn’t sent that should have been. Harkening back to the radio explanation, a listener will never know if a song was meant to play on a channel or if the channel is out of range, and once the record executives hand off the music, they’ve got no idea if the user received the songs without direct feedback from them.

Additionally, while the system is extensible and flexible, instability does occur with high traffic load as subclass after subclass might be constructed to handle further segmentation. This of course leads to the aforementioned instability in addition to increased complexity.

You must keep in mind that while the relationship between the publisher and subscriber in this model may be beneficial, it also comes with its own difficulties when these relationships need to be modulated. While you can certainly work around this, at this point, you’re fighting the very basis of the pattern, rather than any secondary natures — you’re trying to make dehydrated water, and fighting against the nature of a pattern suggests the pattern to be inherently poor.

Also read: Building a Backend for Frontend (BFF) For Your Microservices

5: Server Sent Events

Server Sent Events, or SSE, is a communication protocol much like WebSockets, but with the implication of unidirectional data. In this architecture, the server is consistently sending updates to the client as an automatic process. This was standardized under HTML5 by the W3C, and is thus compatible with any solution that is likewise compatible with HTML5.

Of note is that there is a competing standardization from the Web Hypertext Application Technology Working Group – this is a relic from movement away from “HTML5” and into what WHATWG is calling “HTML Living Standard”. The general working consensus is that, WHATWG’s standardization is prioritized in the rare cases of divergent standards. This could become more of an issue as time marches forward, given that WHATWG was created due to a perceived lack of interest from W3C towards evolving HTML, but for the time being, either standard is generally acceptable.
While simple in theory, Server Sent Events are anything but simple when considering benefits and drawbacks.

Pros

SSE is not bidirectional in its communications — the server is issuing the events in a steady, predictable method. This is hugely beneficial to applications which do not need the two-way communications baked into WebSockets or other such solutions, as this means lower bandwidth, and an allowance for the connection to be temporary rather than always-on during the duration of data transfer. By its nature, the data is being transferred one way, and thus there is no need to wait for data to be returned.

Additionally, at least in theory, SSE is easier to set up in complex situations. You only have to worry about data traveling one direction via one system, thus reducing complexity dramatically. There is no need to define a message exchange protocol, no need to specify data duration or wait times, no need to support bilateral messaging — the single direction saves a lot of complexity.

Cons

That simplicity could be where SSE fails for particular use cases. SSE is a very poor solution for situations that require bidirectional communication, and while this seems obvious, it would surprise many developers to see how many systems actually depend on bidirectional communication for simple functionality.

While much of this can be fixed with workarounds, a developer’s goal in choosing an event-driven protocol should be to find one that works out of the box, not to find a solution that might work if configured properly and given secondary systems upon which to depend.

There is also the issue of security and authentication. While two-way systems can easily use authentication methodologies, SSE handles this using header forwarding. While headers can be manipulated and overridden in many languages and applications, the EventSource object in JavaScript does not natively support this, which would cause many adoptees some major headaches.

Finally, there is a concern over loss of efficiency with over transmitting data. A two-direction system can determine when a client or server disconnects, but SSE can only determine that a client has disconnected after attempting a full data transmission and receiving a noted failure. Because of this, data can be lost rather quickly, and with many failed connections, this loss can mount dramatically over time.

Conclusion

There is no one event-driven solution that works in every use case. While many would argue that event-driven solutions should be REST based, which suggests REST Hooks as the answer, many others would argue that it is entirely situational, and that REST is not always the silver bullet it’s touted to be.

If you are building for scalability with low overhead in a browser environment, WebSockets are a great solution. Conversely, if you’d like those same benefits but are working in a non-browser system, then WebHooks should be your approach. REST Hooks are not only great for RESTful services, they’re also much easier to set up than either, and thus are great in low-time high-rush situations. Pub-Sub can be great if you need to enforce a division between client and server, and this can further be established and controlled in an even stronger way with Server Sent.

Simply put, the best solution will be the one that fits your specific situation and build — any of these solutions, given the correct system, is a great solution. To that end, each solution has a very specific use case.

TLDR Comparison Table

PROTOCOL RELATED TO STANDARD BODY NOTES
WebSockets TCP, HTTP-like IETF, W3C Two-way communication over TCP
Designed for web browsers & web servers
Good for lower overhead scenarios
Supported in all major browsers
Webhooks URI, HTTP - User defined “HTTP callbacks”
Triggered by an event HTTP
Requests are made to Webhook URI
Enables real-time event triggering
REST Hooks HTTP Zapier Lightweight subscription layer
Manipulated by a REST API
Essentially a WebHook in REST
Pub-Sub - - Client subscribes to classes
Bidirectional
Middleman layer between client and server
Loose coupling
Server Sent HTTP, HTML5 , DOM WHATWG, W3C Server constantly sends updates to the client
Unidirectional push notifications as DOM events

大前端周刊 第4期 (本期小编:李丽娇)

基础

文章

  • ECMAScript 6 入门-Symbol
    symbols类型
    推荐人:王祥
    继六种数据类型(Undefined、Null、Boolean、Number、String、Object)后,ES6又新增了Symbols类型。Symbols类型比较抽象,要了解相关的适应场景,可以看这两篇文章。

  • Vue 与 iOS 的组件化
    推荐人:张成斌
    对Vue的组件化有一个非常清晰的讲解。组件化原理,组件化分,组件间传递都有涉及。另外笔者是一名普通的全职 iOS 开发者,还介绍iOS的组件化的东西,对前端和移动端进行了一些对比。

  • SVG Sprite技术介绍
    推荐人:李丽娇
    使用svg文件显示小图标已经成为趋势,随之而来地,svg文件合并也成为必然需求。文中介绍了svg sprite的使用原理,并介绍了多种生成svg sprite的方式来满足偏前端、偏命令、偏设计各类coder的需求。

  • ECharts 统计扩展教程
    推荐人:胡国伟
    ECharts 统计扩展,包含的功能有直方图、聚类、回归、以及常用的汇总统计。通过统计扩展和 ECharts 的结合,可以使大家方便地实现可视分析,也就是将数据分析的结果,通过可视化直观地呈现出来。

  • 前端性能优化相关
    推荐人:陶明
    从多角度进行性能问题剖析,对JavaScript,DOM,CSS都介绍了性能优化方面的问题因素及解决方案;内容介绍不是很详细,例如对于debounce 进行消抖只是简单说明,这方面在第一期成斌有推荐详细的文章

  • JavaScript问题集锦
    推荐人:李志伟
    文章整理了一些比较有价值且常见的JS问题,看似简单,但深究其原理还是很有必要的,相信对你的JS基础功底是个考验。

  • 浅谈 JS 对象之扩展、密封及冻结三大特性
    推荐人:耿少真
    由浅入深讨论JS中对象的扩展、密封及冻结特性,从三种不同的冻结程度介绍了 js 冻结对象的方法。

    扩展特性:
    • Object.isExtensible 方法
    • Object.preventExtensions 方法
      密封特性:
    • Object.isSealed 方法
    • Object.seal 方法
      冻结特性
    • Object.isFrozen 方法
    • Object.freeze 方法
  • 十大经典排序算法
    推荐人:郭俊兵
    排序算法可以分为内部排序和外部排序,内部排序是数据记录在内存中进行排序,而外部排序是因排序的数据很大,一次不能容纳全部的排序记录,在排序过程中需要访问外存。常见的内部排序算法有:插入排序、希尔排序、选择排序、冒泡排序、归并排序、快速排序、堆排序、基数排序等。

  • Javascript模块化编程(一):模块的写法
    Javascript模块化编程(二):AMD规范
    Javascript模块化编程(三):require.js的用法
    推荐人:包京京
    阮一峰的文章最大的好处就是解释的清楚,很多大牛工程师不善表达,自己会但不一定能教得会。
    三篇系列文章介绍了:js模块花的基本概念,AMD规范以及require.js的实践。

大前端周刊 第3期 (本期小编:李志伟)

基础

  • JavaScript系列
    相信作为“前端程序猿(媛)”的你一定了解作用域、原型、原型链、继承、闭包……在前端框架的盛行之下,却让初学者忽略了JS基础的学习,但基础不稳必然限制你的发展空间,当你了解了底层,就能很轻松明白框架的原理。

  • 排序算法
    什么?在这个“用数据说话”的时代,你不懂排序算法?那你算什么男人~算什么男人~ 不对不对 算什么猿人~算什么猿人…咳咳,言归正传,平时开发我们常用的快速排序、冒泡排序、选择排序你是否了解其利弊。除此之外还有什么排序算法呢?快来一起学习吧。

  • Iterator 遍历器
    Iterator为各种不同的数据结构提供了统一的访问机制。它可以提供统一的、简便的接口,使得数据结构的成员按某种次序排列,而es6新增for…of循环,就是由Iterator接口提供消费的。

  • TCP协议简介
    TCP作为互联网核心协议之一,“三次握手”“四次挥手”你是否有所了解?快来完善自己的知识体系吧。
    ps:详解请参考这里

  • 正则表达式
    业务中有很多复杂的逻辑判断?常常嵌套多个if?快来这里学习下吧,熟练掌握正则表达式会使得你的开发效率得到极大提升。

资源整理

文章

  • 一劳永逸的搞定flex布局
    你是否还在使用浮动布局?写各种line-height实现居中?不妨试试flexBox布局,它简单易用的写法可以轻松实现各种布局,让你的布局更快速高效。

  • Vue的数据依赖实现原理简析
    主要从初始化的数据层面上分析了Vue是如何管理依赖来到达数据的动态响应。
    initState的过程中,将props,computed,data等属性通过Object.defineProperty来改造其getter/setter属性,并为每一个响应式属性实例化一个observer观察者。这个observer内部dep记录了这个响应式属性的所有依赖。
    当响应式属性调用setter函数时,通过dep.notify()方法去遍历所有的依赖,调用watcher.update()去完成数据的动态响应。

  • 靠谱程序员必备技能——重构
    当项目变得难以维护,重构便便迫在眉睫,但很多所谓重构仅仅算是重写,随着时间推移,项目再次变得难以维护,周而复始,陷入怪圈。如何避免重构变成重写,本文给了一些很好的建议。

  • 我接触过的前端数据结构与算法
    只要是工程师就必须学好计算机基础,只有这样才能适应计算机技术的快速发展,前端工程师更是如此。

  • Vuex 通俗版教程
    Vuex 类似 Redux 的状态管理器,用来管理Vue的所有组件状态。
    一般在你开发大型单页应用(SPA),会出现多个视图组件依赖同一个状态,来自不同视图的行为需要变更同一个状态。
    遇到以上情况时候,可以考虑使用Vuex,它能把组件的共享状态抽取出来,当做一个全局单例模式进行管理。这样不管你在何处改变状态,都会通知使用该状态的组件做出相应修改。

  • 学习Vue.js源码
    文中介绍了vue项目目录结构和数据绑定实现,没有太深入,但可以作为初步了解。

  • GitHub —— 你不得不上的交友网站
    文章整理了GitHub入门,搭建发布个人博客及个人项目发布,还介绍了一些工具,插件及开源项目;内容比较丰富。

  • 彻底搞清楚javascript中的require、import和export
    通过介绍CMD、AMD、ES6的模块规范,来引申出平时业务中经常用到require、import和export的用法以及含义。

  • 工具推荐
    覆盖率工具 istanbul 替换为 nyc,多进程覆盖率的测试速度提升了几倍。都是同一作者的作品,后者目前活跃度高,并支持前端很多新特性。

1
2
$ npm i nyc --save-dev
$ ./node_modules/.bin/nyc ./node_modules/.bin/mocha

执行单元测试命令后,还会直观的给出代码覆盖率报告,以Flclover为例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
------------------------------------|----------|----------|----------|----------|----------------|
File | % Stmts | % Branch | % Funcs | % Lines |Uncovered Lines |
------------------------------------|----------|----------|----------|----------|----------------|
All files | 79.41 | 66.67 | 61.11 | 81.82 | |
flclover | 100 | 100 | 100 | 100 | |
index.js | 100 | 100 | 100 | 100 | |
flclover/lib | 88.52 | 82.35 | 81.82 | 88.52 | |
application.js | 100 | 100 | 100 | 100 | |
flclover.js | 30 | 0 | 0 | 30 |... 13,14,17,19 |
flclover/lib/middleware/bodyparser | 100 | 100 | 100 | 100 | |
index.js | 100 | 100 | 100 | 100 | |
flclover/lib/middleware/logger | 55.56 | 50 | 50 | 55.56 | |
index.js | 55.56 | 50 | 50 | 55.56 |... 39,42,45,48 |
flclover/lib/utils | 71.43 | 33.33 | 0 | 83.33 | |
index.js | 81.25 | 33.33 | 0 | 100 | 7,10 |
logger.js | 40 | 100 | 0 | 40 | 4,9,13 |
------------------------------------|----------|----------|----------|----------|----------------|