커스텀 구성요소 만들기

개요

Embed API는 여러 기본 구성요소와 함께 제공되며 구성요소를 쉽게 만들 수 있습니다. 이 문서에서는 새로운 맞춤 구성요소를 빌드하는 방법과 애플리케이션에 서드 파티 구성요소를 포함하는 방법을 설명합니다.

커스텀 구성요소 만들기

맞춤 Embed API 구성요소는 gapi.analytics.createComponent를 호출하고 구성요소 이름과 메서드 객체를 전달하여 만듭니다.

createComponent에 전달되는 이름은 구성요소의 생성자 함수 이름이 되며 gapi.analytics.ext에 저장됩니다. 메서드 객체에는 구성요소의 프로토타입에 추가하려는 함수 또는 속성이 포함되어야 합니다.

gapi.analytics.createComponent('MyComponent', {
  execute: function() {
    alert('I have been executed!');
  }
});

구성요소가 생성되면 구성요소 생성자와 함께 new 연산자를 호출하여 구성요소를 사용할 수 있습니다.

// Create a new instance of MyComponent.
var myComponentInstance = new gapi.analytics.ext.MyComponent();

// Invoke the `execute` method.
myComponentInstance.execute() // Alerts "I have been executed!"

초기화 메서드

메서드 객체를 createComponent에 전달하면 구성요소의 프로토타입에 액세스할 수 있지만 구성요소의 생성자에는 액세스할 수 없습니다.

이 문제를 해결하기 위해 새 Embed API 구성요소가 생성되면 initialize라는 메서드가 있는지 자동으로 찾습니다. 이를 찾으면 생성자에 전달된 것과 동일한 arguments로 호출됩니다. 일반적으로 생성자에 넣는 모든 로직을 대신 초기화 메서드에 배치해야 합니다.

다음은 새 MyComponent 인스턴스를 만들 때 일부 기본 속성을 설정하는 예입니다.

gapi.analytics.createComponent('MyComponent', {
  initialize: function(options) {
    this.name = options.name;
    this.isRendered = false;
  }
});

var myComponentInstance = new gapi.analytics.ext.MyComponent({name: 'John'});
alert(myComponentInstance.name); // Alerts "John"
alert(myComponentInstance.isRendered); // Alerts false

상속된 메서드

createComponent 메서드로 생성된 구성요소는 모든 내장 구성요소 (get, set, on, once, off, emit)에서 공유하는 기본 메서드를 자동으로 상속합니다. 이렇게 하면 모든 구성요소가 일관되고 예측 가능한 방식으로 작동합니다.

예를 들어 구성요소에서 사용자 승인을 요구하는 경우 상속된 이벤트 처리 메서드를 사용하여 이를 수행할 수 있습니다.

gapi.analytics.createComponent('MyComponent', {
  initialize: function() {
    this.isRendered = false;
  },
  execute: function() {
    if (gapi.analytics.auth.isAuthorized()) {
      this.render();
    }
    else {
      gapi.analytics.auth.once('success', this.render.bind(this));
    }
  },
  render: function() {
    if (this.isRendered == false) {

      // Render this component...

      this.isRendered = true;
      this.emit('render');
    }
  }
});

var myComponentInstance = new gapi.analytics.ext.MyComponent();

// Calling execute here will delay rendering until after
// the user has been successfully authorized.
myComponentInstance.execute();
myComponentInstance.on('render', function() {
  // Do something when the component renders.
});

라이브러리가 준비될 때까지 기다리는 중

Embed API 스니펫은 라이브러리와 모든 종속 항목을 비동기식으로 로드합니다. 즉, createComponent와 같은 메서드는 즉시 사용할 수 없으며 이러한 메서드를 호출하는 코드는 모든 것이 로드될 때까지 지연되어야 합니다.

Embed API는 라이브러리가 완전히 로드될 때 호출될 콜백을 허용하는 gapi.analytics.ready 메서드를 제공합니다. 맞춤 구성요소를 만들 때는 모든 필수 메서드가 존재하기 전에는 코드가 실행되지 않도록 항상 ready 함수 내에 코드를 래핑해야 합니다.

gapi.analytics.ready(function() {

  // This code will not run until the Embed API is fully loaded.
  gapi.analytics.createComponent('MyComponent', {
    execute: function() {
      // ...
    }
  });
});

서드 파티 구성요소 사용

서드 파티 Embed API 구성요소는 일반적으로 개별 자바스크립트 파일로 패키징되며, 이 파일은 <script> 태그를 사용하여 페이지에 포함할 수 있습니다.

로드 순서가 중요하므로 먼저 Embed API 스니펫을 포함하고 구성요소 스크립트 및 종속 항목을 따라야 합니다.

<!-- Include the Embed API snippet first. -->
<script>
(function(w,d,s,g,js,fjs){
  g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(cb){this.q.push(cb)}};
  js=d.createElement(s);fjs=d.getElementsByTagName(s)[0];
  js.src='https://apis.google.com/js/platform.js';
  fjs.parentNode.insertBefore(js,fjs);js.onload=function(){g.load('analytics')};
}(window,document,'script'));
</script>
<!-- Then include your components. -->
<script src="path/to/component.js"></script>
<script src="path/to/another-component.js"></script>

종속 항목 관리

구성요소에는 d3.js와 같은 차트 라이브러리 또는 moment.js와 같은 날짜 형식 지정 라이브러리와 같은 종속 항목이 있을 수 있습니다. 이러한 종속 항목을 문서화하는 것은 구성요소 작성자에 달려 있으며, 이러한 종속 항목이 충족되는지 확인하는 것은 구성요소 사용자에게 달려 있습니다.