Angular遇上CoffeeScript - NgComponent封装

CoffeeScript是基于JavaScript的一门扩展小巧语言,它需要编译成JavaScript,然后再运行与浏览器或者Nodejs平台。JavaScript由于商业原因10天时间就匆忙诞生,所以存在很多弊病。但如《JavaScript精粹》一书中所说:JavaScript也存在着一颗华丽的心脏,如果我们能避开JavaScript中的“坑”,使用其精华的部分,这将是一门令人爱不释手的语言. 而CoffeeScript则是尝试使用这部分简洁的方式展示JavaScript的这部分优秀的精华,避免那些困扰JavaScript开发者的“坑”.CoffeeScript借鉴于Python和Ruby这两门语言,函数式风格、鸭子类型、OO风格一体的一门简洁语言。

Angularjs从2012年以来是火极一时的前端MVVM框架,它引入了module、双向绑定、依赖注入、Directive、MVVM等机制。更多资料参见博主其他博文。当Angular遇见CoffeeScript这门语言,将会发生什么呢?

想让我们来看一眼笔者利用CoffeeScript对Angular1.x代码的封装后效果。

## controller
class DemoController extends NgComponent
@inject 'demoService'
@controller 'ng.green.demo' __init__: =>
@demoService.getLang().then (data) =>
@lang = data ## service
class DemoService extends NgComponent
@inject '$q'
@service 'ng.green.demo' getLang: =>
data = data : ['JavaScript', 'CoffeeScript', 'TypeScript', 'ES6']
@$q.when(data) ## directive controller
class JsonDumpController extends NgComponent
@inject '$log'
@controller 'ng.green.demo' __init__: =>
@$log.info('This is form directive controller') ## directive
class JsonDumpDirective extends NgComponent
@inject '$timeout', '$http', '$cacheFactory', '$log'
@directive 'ng.green.demo'
restrict: 'EA'
templateUrl: '/jsonDump.html'
scope:
json: "="
controller: 'JsonDumpController'
link: (scope, elm, iAttrs) =>
@$timeout (() => @$log.info '$timeout & $log injector worked on link function!' ), 100

有了上面的对controller、service、directive的定义,则我们可以如下方式使用:

<div ng-app="ng.green.demo" ng-controller="DemoController as demo" class="container">
<json-dump json="demo.lang"></json-dump>
<script type="text/ng-template" id="/jsonDump.html">
<hr />
<pre></pre>
</script>
</div>

不知各位看官对如上代码感觉如何?是不是更简化、语义化、有点ng的感觉。其中笔者还有意模仿Python,如init作为初始化方式。在这里每个class会自声明组件类型,以及声明式注入,module自注册。

不管如何看,下面我来看看NgComponent到底做了什么?

class NgComponent
@controller: (moduleName, moduleResolver) ->
componentName = @$$componentName(true)
angular.module(moduleName, moduleResolver).controller componentName, @ @service: (moduleName, moduleResolver) ->
componentName = @$$componentName()
angular.module(moduleName, moduleResolver).service componentName, @ @directive: (moduleName, moduleResolver) ->
componentName = @$$componentName().replace('Directive','')
directiveClass = @
directiveFactory = (args...) ->
new directiveClass(args...)
directiveFactory.$inject = @$inject
angular.module(moduleName, moduleResolver).directive componentName, directiveFactory @$$componentName: (upperCaseFirstLetter = false) ->
# regex for ie
componentName = @name || @toString().match(/function\s*(.*?)\(/)?[1]
if upperCaseFirstLetter
firstLetter = componentName.substr(0,1).toUpperCase()
else
firstLetter = componentName.substr(0,1).toLowerCase()
(componentName = "#{firstLetter}#{componentName.substr(1)}") unless upperCaseFirstLetter
componentName @inject: (args...) ->
@$inject = args constructor: (args...) ->
for key, index in @constructor.$inject
@[key] = args[index] @__init__?()

在NgComponent中定义了controller、service、directive注册接口,这里可以是声明创建module,也可以是在已声明的module上注册这些组件类型。对于组件命名也才采用了约定胜于配置,它们都以class类型为基础,controller为首字母大写的驼峰命名,service则首字母小写驼峰命名,directive则会去掉Directive标记并首字母小写注册。

同时这里也声明了@inject方法,使得我们可以在定义在类型之上定义$inejct属性,Angular的注入声明。对于Angular的注入服务,在构造函数中会将他们一一添加到当前类实例对象之上。在依赖添加完毕后,也会调用对象初始化方法,这里是模拟Python的init

Demo效果可以在codepen查看 http://codepen.io/greengerong/pen/EVVQZg?editors=101

本文笔者的突发奇想,希望能给读者一些启发,也许你还有更好的DSL封装,欢迎多多交流。

最新文章

  1. Maven环境配置
  2. ios安装app提示【未受信任的企业级开发者】。在设置中信任此开发者
  3. 深入理解C语言
  4. VS2015新建asp.net core站点
  5. 删除某一BSC在某一时间段内的数据
  6. Tomcat内存设置
  7. MySQL下划线特殊字符(Like 语句)
  8. Cocos2d-x利用CCHttpRequest获取网络图片并显示
  9. PHP扩展开发(1):入门
  10. IntraWeb.v14.0.32安装及破解指南
  11. Python 番外 消息队列设计精要
  12. Android_Dialog cancle 和dismiss 区别
  13. JavaScript插件——弹出框
  14. python 单行写法
  15. php处理手机号中间的四位为星号****
  16. BZOJ1059 [ZJOI2007]矩阵游戏 二分图匹配 匈牙利算法
  17. UVa 902 - Password Search
  18. C4D 计算体积和表面积插件
  19. (zxing.net)一维码MSI的简介、实现与解码
  20. 用java代码在创建hbase表时指定region的范围

热门文章

  1. 採用Android中的httpclient框架发送post请求
  2. 【原创】leetCodeOj --- Binary Tree Right Side View 解题报告
  3. 【SICP读书笔记(二)】使用过程来黏合数据 —— 酷炫吊的消息传递机制
  4. POJ 1236 Network of Schools(强连通分量)
  5. uva 10817 Headmaster&amp;#39;s Headache 出发dp 位计算
  6. BZOJ 2007 NOI2010 海拔高度 最小减产计划
  7. 返璞归真 asp.net mvc (11) - asp.net mvc 4.0 新特性之自宿主 Web API, 在 WebForm 中提供 Web API, 通过 Web API 上传文件, .net 4.5 带来的更方便的异步操作
  8. Lua 脚本语法说明(转)
  9. c++头
  10. 矢量编程——随着MNIST案例