angularjs DI简单模拟
简单模拟了一下angularjs的DI.
注入器,简单思路: 1 Injector容器供用户注入
2 监听onload事件,找到controller,然后执行对应方法
var Injector = (function(){ window.onload = compile; function compile(){ $("[controller]").each(function(ctrl){ var methodName = $(this).attr("controller"); var method = window[methodName]; var methodStr = method.toString(); var injectionstr = methodStr.substring(methodStr.indexOf("(")+1,methodStr.indexOf(")")).split(","); var injectionArr = []; for(var i=0;i<injectionstr.length;i++){ injectionArr.push(Injector.get(injectionstr[i])); } method.apply(this,injectionArr); }); } return { factory :function(name,instance){ this[name] = instance(); }, get :function(name){ return this[name]; } } }())
测试:
<html> <head> <script src="jquery.js"></script> <script src="injector.js"></script> <script> Injector.factory("$timeService",function(){ return { printTime : function(){ console.log(new Date()); } } }); function ctrl($timeService){ $timeService.printTime(); } </script> </head> <body> <div controller="ctrl"> </div> </body> </html>
结果:Mon Sep 09 2013 19:28:16 GMT+0800 (澳大利亚西部标准时间)