Anglejs 배열의 매개변수 전달 방법을 구문 분석합니다.

巴扎黑
풀어 주다: 2017-08-14 14:09:38
원래의
1727명이 탐색했습니다.

이 글은 주로angularjs의 배열 매개변수 전달 방식의 간단한 구현을 소개합니다. 편집자는 꽤 좋다고 생각해서 지금 공유하고 참고용으로 제공하겠습니다. 에디터를 따라가서 살펴볼까요

Angularjs를 처음 배울 때 배열 매개변수 전달 방식(['a', 'b', function(a,b){}])이 매우 궁금했습니다. 구현됐나요? 나중에는 일이 너무 바빠서 이 문제를 점차 잊어버렸습니다.

오늘은 할 일이 없어서 이런 질문을 생각해봤습니다. 가장 쉬운 방법은 그의 소스 코드를 보는 것입니다. 아쉽게도 제 E-writing은 디자인 논리는 말할 것도 없고 영어 댓글만 읽어도 머리가 아플 정도입니다. 닫힌 문 뒤에서 자동차를 만들려고 노력하고 마침내 자동차를 만듭니다.

자신만의 자동차를 만들려면 자신의 이름을 지참하고(이름의 병음 첫 글자를 따서) mqyJs라고 불러야 합니다. 시연 호출 방법은 다음과 같습니다.


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

The 핵심 부분은 다음과 같습니다.

//框架开设
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];
  }
};
//框架结束
로그인 후 복사

serviceRegister를 통해 $http ofangularjs와 같은 서비스를 등록할 수 있습니다.

//插件开始
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());
});
로그인 후 복사

위 내용은 Anglejs 배열의 매개변수 전달 방법을 구문 분석합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!