Last active
August 29, 2015 14:12
-
-
Save lsongdev/cca68cf4ec89bc10772d to your computer and use it in GitHub Desktop.
Dependency injection Demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <html> | |
| <head> | |
| <title>Dependency injection Demo</title> | |
| <script charset="utf-8"> | |
| /** | |
| * [依赖注入核心定义] | |
| * @param {[type]} win [description] | |
| * @param {[type]} undefined [description] | |
| * @return {[type]} [description] | |
| */ | |
| ;(function(win, undefined){ | |
| /** | |
| * [obj 用于存储定义的对象] | |
| * @type {Object} | |
| */ | |
| var obj = { }; | |
| /** | |
| * [def 定义依赖服务] | |
| * @param {[type]} key [description] | |
| * @param {[type]} val [description] | |
| * @return {[type]} [description] | |
| */ | |
| var def = function(key, val){ | |
| obj[ '$' + key ] = val; | |
| }; | |
| /** | |
| * [run 自动依赖注入并执行] | |
| * @param {Function} fn [description] | |
| * @return {[type]} [description] | |
| */ | |
| var run = function run(fn){ | |
| var deps = fn | |
| .toString() | |
| .match(/([^\(\)]+)/g)[1] | |
| .split(','); | |
| fn.apply(fn, deps.map(function(name, key){ | |
| return obj[ name.trim() ]; | |
| })); | |
| }; | |
| //expose | |
| win.def = def; | |
| win.run = run; | |
| })(window); | |
| </script> | |
| <script charset="utf-8"> | |
| //demo code | |
| /** | |
| * [定义 alert 服务] | |
| * @return | |
| */ | |
| def('alert', function(msg){ | |
| alert(msg); | |
| }); | |
| /** | |
| * [定义 name 服务] | |
| */ | |
| def('name', 'lsong'); | |
| /* | |
| 执行 function 时,自动检测回调函数的依赖项 | |
| 注入到函数的参数中,并执行函数 | |
| */ | |
| run(function($alert, $name){ | |
| $alert($name); | |
| }); | |
| </script> | |
| </head> | |
| <body></body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment