angular1.x和ES6开发风格

一、Module

ES6有自己的模块机制,所以我们要通过使用ES6的模块机制来淡化ng的框架,使得各业务逻辑层的看不出框架的痕迹,具体的做法是:
  • 把各功能模块的具体实现代码独立出来。
  • module机制作为一个壳子,对功能模块进行封装。
  • 每个功能分组,使用一个总的壳子来包装,减少上级模块的引用成本。
  • 每个壳子文件把module的name属性export出去。
举例来说,我们有一个moduleA,里面有serviceA,serviceB,那么,就有这样一些文件:
serviceA的实现,service/a.js
export default class ServiceA {}

serviceB的实现,service/b.js

export default class ServiceB {}

moduleA的壳子定义,moduleA.js

import ServiceA from './services/a';
import ServiceB from './services/b';
export default angular.module('moduleA'[])
.service('ServiceA', ServiceA)
.service('ServiceB', ServiceB)
.name;

存在一个moduleB要使用moduleA:

import moduleA from './moduleA';
export default angular.module('moduleB', [moduleA]).name;

二、Controller

ng1.2开始提供了controllerAs的语法,自此Controller终于能变成一个纯净的ViewModel(视图模型)了,而不像之前一样混入过多的$scope痕迹。
例如:
HTML
<div ng-controller="AppCtrl as app">
<div ng-bing="app.name"></div>
<button ng-click="app.getName">get app name</button>
</div>

controller AppCtrl.js

export default class AppCtrl {
constructor() {
this.name = 'angualr$es6';
}
getName() {
return this.name;
}
}

module

import AppCtrl from './AppCtrl';
export default angular.module('app', [])
.controller('AppCtrl', AppCtrl)
.name;

三、Component(Directive)

指令主要包含了一个ddo(Directive Definition Object),所以本质上这是一个对象,我们可以给它构建一个类。
export default class DirectiveA {}

DDO上面的东西大致可以分为两类,属性和方法,所以就在构造函数里这样定义:

constructor() {
this.template = template;
this.restrict = 'E';
}

接下来就是controller和link,compile等函数了,比如controller,可以实现一个普通的controller类,然后赋值到controller属性上来:

this.controller = ControllerA;

写directive的时候,尽量使用controllerAs这样的语法,这样controller可以清晰一些,不必注入$scope,而且还可以使用bingToController属性,把在指令attr上定义的值或方法传递到controller实例上来。接下来我们使用三种方法来定义指令


1、定义一个类(ddo),然后在定义指令的工厂函数中返回这个类的实例。

我们要做一个日期控件,合起来就是这样
import template from '../template/calendar.html';
import CalendarCtrl from '../controllers/calendar'; import '../css/calendar.css'; export default class CalendarDirective{
constructor() {
this.template = template;
this.restrict = 'E'; this.controller = CalendarCtrl;
this.controllerAs = 'calendarCtrl';
this.bingToController = true; this.scope = {
minDate: '=',
maxDate: '=',
selecteDate: '=',
dateClick: '&'
};
} link(scope) {
//这个地方引入了scope,应尽量避免这种做法,
//但是搬到controller写成setter,又会在constructor之前执行
scope.$watch('calendarCtrl.selecteDate', newDate => {
if(newDate) {
scope.calendarCtrl.calendar.year = newDate.getFullYear();
scope.calendarCtrl.calendar.month = newDate.getMonth();
scope.calendarCtrl.calendar.date = newDate.getDate(); }
});
}
}

然后在module定义的地方:

import CalendarDirective from './directives/calendar';

export default angular.module('components.form.calendar', [])
.directive('snCalendar', () => new CalendarDirective())
.name;

2、直接定义一个ddo对象,然后传给指令

同样以datepicker组件为例,先定义一个controller
// DatePickerCtrl.js
export default class DatePickerCtrl {
$onInit() {
this.date = `${this.year}-${this.month}`;
} getMonth() {
...
} getYear() {
...
}
}

注意,这里先写了controller而不是link/compile方法,原因在于一个数据驱动的组件体系下,我们应该尽量减少对DOM操作,因此理想状态下,组件是不需要link或compile方法的,而且controller在语义上更贴合mvvm架构。

在模块定义的地方我们可以这样使用:
import template from './date-picker-tpl.html';
import controller from './DatePickerCtrl'; const ddo = {
restrict: 'E',
template, //es6对象简写
controller,
controllerAs: '$ctrl',
bingToController: {
year: '=',
month: '='
} }; export default angular.module('components.datePicker', [])
.directive('dataPicker', ddo)
.name;

在整个系统设计中只有index.js(定义模块的地方)是框架可识别的,其它地方的业务逻辑都不应该出现框架的影子,这样方便移植。


3、component

1.5之后提供了一个新的语法moduleInstance.component,它是moduleInstance.directive的高级封装版,提供了更简洁的语法,同时也是未来组件应用的趋势。例如
bingToController -> bindings的变化,而且默认controllerAs = ‘$ctrl’,但是它只能定义自定义标签,不能定义增强属性,而且component定义的组件都是isolated scope。

1.5版本还给组件定义了相对完整的生命周期钩子,而且提供了单向数据流的方式,以上例子可以写成下面这样子:

//DirectiveController.js
export class DirectiveController {
$onInit() { } $onChanges(changesObj) { } $onDestroy() { } $postLink() { }
} //index.js
import template from './date-picker-tpl.html';
import controller from './DatePickerCtrl'; const ddo = {
template,
controller,
bindings: {
year: '<',
month: '<'
}
}; export default angular.module('components.datepicker', [])
.component('datePicker', ddo)
.name;

4、服务

先来说一下在ES6中通过factory和service来定义服务的方式。
serviceA的实现,service/a.js
export default class ServiceA {}

serviceA的模块包装器moduleA的实现

import ServiceA from './service/a';

export angular.module('moduleA', [])
.service('ServiceA', ServiceA)
.name;

factoryA的实现,factory/a.js

import EntityA from './model/a';

export default function FactoryA {
return new EntityA();
}

factoryA的模块包装器moduleA的实现

import FactoryA from './factory/a';

export angular.module('modeuleA', [])
.factory('FactoryA', FactoryA)
.name;

对于依赖注入我们可以通过以下方式来实现:

controller/a.js
export default class ControllerA {
constructor(ServiceA) {
this.serviceA = ServiceA;
}
} ControllerA.$inject = ['ServiceA'];

import ControllerA from './controllers/a';

export angular.module('moduleA', [])
.controller('ControllerA', ControllerA);

对于constant和value,可以直接使用一个常量来代替。

Contant.js
export const VERSION = '1.0.0';

5、filter

angular中filter做的事情有两类:过滤和格式化,归结起来就是一种数据的变换工作,过度使用filter会让你的额代码在不自知的情况下走向混乱。所以我们可以自己去写一系列的transformer来做数据处理。
import { dateFormatter } './transformers';
export default class Controller {
constructor() {
this.data = [1,2,3,4]; this.currency = this.data
.filter(v => v < 4)
.map(v => '$' + v); this.date = Date.now();
this.today = dateFormatter(this.date);
}
}

6、消除$scope,淡化框架概念

1、controller的注入

1.2之后有了controllerAS的语法,我们可以这么写。
<div ng-controller="TestCtrl as testCtrl">
<input ng-model="testCtrl.aaa">
</div>

xxx.controller("TestCtrl", [function() {
this.aaa = 1;
}]);

实际上框架会做一些事情:

$scope.testCtrl = new TestCtrl();

对于这一块,把那个function换成ES6的类就可以了。

2、依赖属性的计算

在$scope上,除了有$watch,$watchGroup,$watchCollection,还有$eval(作用域上的表达式求值)这类东西,我们必须想到对它们的替代办法。

一个$watch的典型例子
$scope.$watch("a", function(val) {
$scope.b = val + 1;
});

我们可以直接使用ES5的setter和getter来定义就可以了。

class A {
set a(val) { //a改变b就跟着改变
this.b = val + 1;
}
}

如果有多个变量要观察,例如

$scope.$watchGroup(["firstName", "lastName"], function(val) {
$scope.fullName = val.join(",");
});

我们可以这样写

class Controller {

    get fullName() {
return `${this.firstName} ${this.lastName}`;
}
}

html

<input type="text" ng-model="$ctrl.firstName">
<input type="text" ng-model="$ctrl.lastName"> <span ng-bind="$ctrl.fullName"></span>

3、事件冒泡和广播

在$scope上,另外一套常用的东西是$emit,$broadcast,$on,这些API其实是有争议的,因为如果说做组件的事件传递,应当以组件为单位进行通信,而不是在另外一套体系中。所以我们也可以不用它,比较直接的东西通过directive的attr来传递,更普遍的东西用全局的类似Flux的派发机制去通信。

根作用域的问题也是一样,尽量不要去使用它,对于一个应用中全局存在的东西,我们有各种策略去处理,不必纠结于$rootScope。

4、指令中$scope

参见上文关于指令的章节。

7、总结

对于整个系统而言,除了angular.module,angular.controller,angular.component,angular.directive,angular.config,angular.run以外,都应该实现成与框架无关的,我们的业务模型和数据模型应该可以脱离框架而运作,当做完这层之后,上层迁移到各种框架就只剩下体力活了。

一个可伸缩的系统构架,确保下层业务模型/数据模型的纯净都是有必要的,这样才能提供上层随意变化的可能,任何模式下的应用开发,都应具备这样一个能力。

参考链接:






angular1.x + ES6开发风格记录的更多相关文章

  1. ES6深入学习记录(三)编程风格

    今天学习阮一峰ES6编程风格,其中探讨了如何将ES6的新语法,运用到编码实践之中,与传统的JavaScript语法结合在一起,写出合理的.易于阅读和维护的代码. 1.块级作用域 (1)let 取代 v ...

  2. [webpack] 配置react+es6开发环境

    写在前面 每次开新项目都要重新安装需要的包,简单记录一下. 以下仅包含最简单的功能: 编译react 编译es6 打包src中入口文件index.js至dist webpack配置react+es6开 ...

  3. webpack+react+redux+es6开发模式

    一.预备知识 node, npm, react, redux, es6, webpack 二.学习资源 ECMAScript 6入门 React和Redux的连接react-redux Redux 入 ...

  4. iOS开发之记录用户登录状态

    iOS开发之记录用户登录状态 我们知道:CoreData的配置和使用步骤还是挺复杂的.但熟悉CoreData的使用流程后,CoreData还是蛮好用的.今天要说的是如何记录我们用户的登陆状态.例如微信 ...

  5. 开发错误记录8:Unable to instantiate application com

    开发错误记录8:Unable to instantiate application com.android.tools.fd.runtime.BootstrapApplication 这是因为在And ...

  6. 【转】使用gulp 进行ES6开发

    原谅地址:https://segmentfault.com/a/1190000004394726 一说起ES6,总会顺带看到webpack.babel.browserify还有一些认都不认识的blab ...

  7. Arduino单片机使用和开发问题记录(转)

    源:Arduino单片机使用和开发问题记录 1.将程序上传到板子时Arduino IDE提示“avrdude: stk500_getsync(): not in sync: resp=0x00” 网上 ...

  8. webpack+react+redux+es6开发模式---续

    一.前言 之前介绍了webpack+react+redux+es6开发模式 ,这个项目对于一个独立的功能节点来说是没有问题的.假如伴随着源源不断的需求,前段项目会涌现出更多的功能节点,需要独立部署运行 ...

  9. IOS开发之记录用户登陆状态,ios开发用户登陆

    IOS开发之记录用户登陆状态,ios开发用户登陆 上一篇博客中提到了用CoreData来进行数据的持久化,CoreData的配置和使用步骤还是挺复杂的.但熟悉CoreData的使用流程后,CoreDa ...

随机推荐

  1. 如何加固Linux系统

    如何加固Linux系统 一. 账户安全 1.1 锁定系统中多余的自建帐号 检查方法: 执行命令 #cat /etc/passwd #cat /etc/shadow 查看账户.口令文件,与系统管理员确认 ...

  2. JDBC操作数据库之删除数据

    删除数据使用的SQL语句为delete语句,如果删除图书id为1的图书信息,其SQL语句为: delete from book where id=1 在实际开发中删除数据通常使用PreparedSta ...

  3. response对象的使用

    使用response对象提供的sendRedirect()方法可以将网页重定向到另一个页面.重定向操作支持将地址重定向到不同的主机上,这一点与转发是不同的.在客户端浏览器上将会得到跳转地址,并重新发送 ...

  4. 关于Android WebView上传文件的解决方案

    我们在开发需求的时候,难免会接入一下第三方的H5页面,有些H5页面是具有上传照片的功能,Android 中的 WebView是不能直接打开文件选择弹框的 接下来我讲简单提供一下解决方案,先说一下思路 ...

  5. 关于IOS的屏幕适配(iPhone)——Auto Layout和Size Classes

    Auto Layout和Size Classes搭配使用极大的方便了开发者,具体如何使用Auto Layout和Size Classes大家可以参考其他文章或者书籍,这里只提一点,在我们设置Size ...

  6. linux free命令解读

    $ free -m total used free shared buffers cached Mem: 1002 769 232 0 62 421 -/+ buffers/cache: 286 71 ...

  7. FPGA在其他领域的应用(四)

    工业领域: 从工厂和过程自动化到能源基础设施和机器视觉系统,工业产品有助于改善我们的世界.产品必须安全.可靠.适应性强,而且耐用.同时,商业成功要求你在激烈竞争的市场中行动迅速,同时降低总成本. 英特 ...

  8. Cmder 软件中修改λ符号方法

    以前的版本 网上都有,我就不介绍了,  只介绍现在的 1. 打开Cmder软件安装位置 2. 打开vendor文件夹 profile.ps1文件 3. 找到第77行  Write-Host " ...

  9. 平板不能设置代理的情况下利用随身wifi进行http代理访问

    需求来源:平板或手机是个封闭系统无法给wifi设置代理,需要利用filllder进行抓包,内容篡改等实验 拥有硬件资源:PC机器 + 小米随身wifi 方案1: NtBind Dns + Nginx ...

  10. angular添加,查找与全部删除

    <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title&g ...