커스텀 구성요소 만들기

개요

Embed API는 여러 기본 제공 구성요소와 함께 제공되며 이를 통해 손쉽게 자체 구성요소를 만들 수 있습니다. 이 문서에서는 새 커스텀 구성요소를 빌드하는 방법과 애플리케이션에 타사 구성요소를 포함하는 방법을 설명합니다.

맞춤 구성요소 만들기

Custom 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와 같은 날짜 서식 라이브러리가 있을 수 있습니다. 이러한 종속 항목을 문서화하는 것은 구성요소 작성자가 담당하고 종속 항목이 충족되도록 하는 것은 구성요소 사용자에게 달려 있습니다.