angular1.x + ES6开发风格记录
angular1.x和ES6开发风格
一、Module
- 把各功能模块的具体实现代码独立出来。
- module机制作为一个壳子,对功能模块进行封装。
- 每个功能分组,使用一个总的壳子来包装,减少上级模块的引用成本。
- 每个壳子文件把module的name属性export出去。
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
<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)
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对象,然后传给指令
// 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版本还给组件定义了相对完整的生命周期钩子,而且提供了单向数据流的方式,以上例子可以写成下面这样子:
//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、服务
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;
对于依赖注入我们可以通过以下方式来实现:
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,可以直接使用一个常量来代替。
export const VERSION = '1.0.0';
5、filter
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的注入
<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("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、总结
参考链接:
总结
以上是生活随笔为你收集整理的angular1.x + ES6开发风格记录的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 上传工程到github
- 下一篇: spring transaction源码