详解angularjs的数组传参方式的简单实现


Posted in Javascript onJuly 28, 2017

初学 angularjs时,对 数组传参方式感到很好奇([‘a', ‘b', function(a,b){}]),它到底怎么实现的呢?后来由于工作很忙,对这个问题也就慢慢忘记了。

今天闲来无事,有想到了这个问题。最简单的方法就是查看他的源代码。无奈本人E文不好,不说看他的设计逻辑,仅看英文注释就够我头疼了。尝试闭门造车,最终竟然把车造出来了。

既然自己造的车,就要带上自己的名(取姓名拼音第一个字母),就叫他mqyJs把,下面是演示的调用方法:

var app2 = mqyJs.applicationCreate([{ name: '直接传入SCOPE' }, '$hello', '$world', function($scope, $hello, $world) {
  return $scope.name + ": " + $hello.name + $world.name;
}]);

核心部分如下:

//框架开设
var mqyJs = {
  //服务注册
  servicesList: {},
  servicesRegister: function(name, value) {
    this.servicesList[name] = value;
  },
  //应用创建
  applicationList: [],
  applicationCreate: function(_opts, _args) {
    if (!_args) {
      _args = _opts;
      _opts = {}
    }
    _opts.scope = _opts.scope || {
      name: 'SCOPE没有设置'
    };
    if (!(_args instanceof Array)) {
      _args = ['$scope', _args];
    }
    if (typeof _args[_args.length - 1] != 'function') {
      throw new Error('参数中没有指定运行函数');
    }
    _args.map((arg, index) => {
      if (typeof arg == 'string') {
        if (arg === '$scope') {
          _args[index] = _opts.scope;
        } else {
          if (!!arg && !(arg in this.servicesList)) {
            throw new Error('插件:' + arg + ' 还没有注册');
          }
          _args[index] = this.servicesList[arg];
        }
      }
    });
    return this.applicationList[this.applicationList.push({
      run: function(callback) {
        if (typeof callback != 'function') {
          callback = function(_opts) { return _opts; }
        }
        return callback(_args[_args.length - 1].apply(null, _args));
      }
    }) - 1];
  }
};
//框架结束

通过 servicesRegister,可以注册 服务,比如 angularjs 的 $http;

//插件开始
mqyJs.servicesRegister('$hello', {
  name: '你好'
});
mqyJs.servicesRegister('$world', {
  name: '世界'
});
mqyJs.servicesRegister('$china', {
  name: '中国'
});
//插件结束

最终,对所有注册的应用,自动执行

/**
 * 初始化完成后系统自动运行
 * 比如网页中 放到 window.onload
 */
mqyJs.applicationList.map(function(app, index) {
  console.log('自动调用 -> APP #' + index + ' -> ' + app.run());
});

尝试跑一下代码,能自动识别参数类型,完美执行。

不传入 $scope 时,程序会自动创建一个 $scope。

//演示代码 开始
var app = mqyJs.applicationCreate(['$scope', '$hello', '$china', function($scope, $hello, $china) {
  return $scope.name + ": " + $hello.name + $china.name;
}]);


var app2 = mqyJs.applicationCreate([{ name: '直接传入SCOPE' }, '$hello', '$world', function($scope, $hello, $world) {
  return $scope.name + ": " + $hello.name + $world.name;
}]);

 

var app3 = mqyJs.applicationCreate([{ name: 'world也直接传入' }, '$hello', { name: '地球' }, function($scope, $hello, $world) {
  return $scope.name + ": " + $hello.name + $world.name;
}]);


var app4 = mqyJs.applicationCreate(function($scope) {
  return $scope.name;
});

var opts = {
  scope: {
    name: '自定义SCOPE'
  }
};
var app5 = mqyJs.applicationCreate(opts, function($scope) {
  return $scope.name;
});

app4.run(function(result) {
  console.log('手动调用 -> RESULT -> ' + result);
});

//演示代码 结束

为了方便测试,再把代码重新写一遍,直接复制下面的代码到 浏览器控制台即可测试

//框架开设
var mqyJs = {
  //服务注册
  servicesList: {},
  servicesRegister: function(name, value) {
    this.servicesList[name] = value;
  },
  //应用创建
  applicationList: [],
  applicationCreate: function(_opts, _args) {
    if (!_args) {
      _args = _opts;
      _opts = {}
    }
    _opts.scope = _opts.scope || {
      name: 'SCOPE没有设置'
    };
    if (!(_args instanceof Array)) {
      _args = ['$scope', _args];
    }
    if (typeof _args[_args.length - 1] != 'function') {
      throw new Error('参数中没有指定运行函数');
    }
    _args.map((arg, index) => {
      if (typeof arg == 'string') {
        if (arg === '$scope') {
          _args[index] = _opts.scope;
        } else {
          if (!!arg && !(arg in this.servicesList)) {
            throw new Error('插件:' + arg + ' 还没有注册');
          }
          _args[index] = this.servicesList[arg];
        }
      }
    });
    return this.applicationList[this.applicationList.push({
      run: function(callback) {
        if (typeof callback != 'function') {
          callback = function(_opts) { return _opts; }
        }
        return callback(_args[_args.length - 1].apply(null, _args));
      }
    }) - 1];
  }
};
//框架结束
//插件开始
mqyJs.servicesRegister('$hello', {
  name: '你好'
});
mqyJs.servicesRegister('$world', {
  name: '世界'
});
mqyJs.servicesRegister('$china', {
  name: '中国'
});
 
var app = mqyJs.applicationCreate(['$scope', '$hello', '$china', function($scope, $hello, $china) {
  return $scope.name + ": " + $hello.name + $china.name;
}]);


var app2 = mqyJs.applicationCreate([{ name: '直接传入SCOPE' }, '$hello', '$world', function($scope, $hello, $world) {
  return $scope.name + ": " + $hello.name + $world.name;
}]);


var app3 = mqyJs.applicationCreate([{ name: 'world也直接传入' }, '$hello', { name: '地球' }, function($scope, $hello, $world) {
  return $scope.name + ": " + $hello.name + $world.name;
}]);


var app4 = mqyJs.applicationCreate(function($scope) {
  return $scope.name;
});

var opts = {
  scope: {
    name: '自定义SCOPE'
  }
};
var app5 = mqyJs.applicationCreate(opts, function($scope) {
  return $scope.name;
});

app4.run(function(result) {
  console.log('手动调用 -> RESULT -> ' + result);
});
 
//插件结束
mqyJs.applicationList.map(function(app, index) {
  console.log('自动调用 -> APP #' + index + ' -> ' + app.run());
});

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
取键盘键位ASCII码的网页
Jul 30 Javascript
jquery下动态显示jqGrid以及jqGrid的属性设置容易出现问题的解决方法
Oct 22 Javascript
与jquery serializeArray()一起使用的函数,主要来方便提交表单
Jan 31 Javascript
JS高级调试技巧:捕获和分析 JavaScript Error详解
Mar 16 Javascript
JavaScript的RequireJS库入门指南
Jul 01 Javascript
用原生js统计文本行数的简单示例
Aug 19 Javascript
ReactNative中使用Redux架构总结
Dec 15 Javascript
JavaScript继承定义与用法实践分析
May 28 Javascript
JS实现的字符串数组去重功能小结
Jun 17 Javascript
highcharts.js数据绑定方式代码实例
Nov 13 Javascript
JavaScript实现PC端四格密码输入框功能
Feb 19 Javascript
js实现小星星游戏
Mar 23 Javascript
js 获取html5的data属性实现方法
Jul 28 #Javascript
jQuery获取table表中的td标签(实例讲解)
Jul 28 #jQuery
浅谈JS中的常用选择器及属性、方法的调用
Jul 28 #Javascript
js原生代码实现轮播图的实例讲解
Jul 28 #Javascript
js弹性势能动画之抛物线运动实例详解
Jul 27 #Javascript
js学习总结之dom2级事件基础知识详解
Jul 27 #Javascript
Angular指令之restict匹配模式的详解
Jul 27 #Javascript
You might like
Ajax+PHP边学边练 之五 图片处理
2009/12/03 PHP
PHP获取数组中某元素的位置及array_keys函数应用
2013/01/29 PHP
详解PHP中strlen和mb_strlen函数的区别
2014/03/07 PHP
php下载文件超时时间的设置方法
2016/10/06 PHP
JS获取IUSR_机器名和IWAM_机器名帐号的密码
2006/12/06 Javascript
IE与firefox下Dhtml的一些区别小结
2009/12/02 Javascript
JavaScript 学习笔记(四)
2009/12/31 Javascript
JQuery 操作Javascript对象和数组的工具函数小结
2010/01/22 Javascript
jquery validate使用攻略 第四步
2010/07/01 Javascript
jQueryUI如何自定义组件实现代码
2010/11/14 Javascript
jquery中dom操作和事件的实例学习 仿yahoo邮箱登录框的提示效果
2011/11/30 Javascript
js获取浏览器的可视区域尺寸的实现代码
2011/11/30 Javascript
Javascript模块化编程详解
2014/12/01 Javascript
JS实现自适应高度表单文本框的方法
2015/02/25 Javascript
javascript实现超炫的向上滑行菜单实例
2015/08/03 Javascript
AngularJS监听路由变化的方法
2017/03/07 Javascript
微信小程使用swiper组件实现图片轮播切换显示功能【附源码下载】
2017/12/12 Javascript
node+koa2+mysql+bootstrap搭建一个前端论坛
2018/05/06 Javascript
Angular4 反向代理Details实践
2018/05/30 Javascript
详解vue-router 命名路由和命名视图
2018/06/01 Javascript
浅谈vue加载优化策略
2019/03/19 Javascript
解决Layui数据表格的宽高问题
2019/09/28 Javascript
[02:57]2014DOTA2国际邀请赛-观众采访
2014/07/19 DOTA
[01:00:14]DOTA2官方TI8总决赛纪录片 真视界True Sight
2019/01/16 DOTA
python字符串,数值计算
2016/10/05 Python
Python判断有效的数独算法示例
2019/02/23 Python
Django异步任务之Celery的基本使用
2019/03/23 Python
Python3.5集合及其常见运算实例详解
2019/05/01 Python
python中count函数简单的实例讲解
2020/02/06 Python
Python递归函数特点及原理解析
2020/03/04 Python
Python如何用wx模块创建文本编辑器
2020/06/07 Python
使用AJAX和Django获取数据的方法实例
2020/10/25 Python
2015年小学开学寄语
2015/02/27 职场文书
2015年社区中秋节活动总结
2015/03/23 职场文书
Tomcat用户管理的优化配置详解
2022/03/31 Servers
vue里使用create, mounted调用方法
2022/04/26 Vue.js