JavaScript API

callback

以下オブジェクトを宣言することで callback を登録することがでます。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
// 初期化
initialize: function() {
},
// ユーザーが返答した際に呼び出されるコールバック
onReply: function(script, reply) {
},
// formが表示された(インタラクションが開始された)時。
onShowForm: function () {
},
// scriptのbodyとしてtemplateを指定した場合ここで変数を埋め込む
// 下記「テンプレートエンジンへのアクセス」を参照
render: function(script, template) {
}
}

このオブジェクトは、以下の擬似コードのように Object.create のパラメーターとして渡される。

1
2
3
4
5
6
7
8
9
10
11
12
var jsApi = new function() {
return Object.create({
initialize: function() {
this.mymethod();
},
//...
// mymethodは this 以下の scopeに定義される
mymethod: function() {
}
});
}

初期化callbackを利用したチャットの自動スタート

以下のように、初期化のcallback内で showChat を呼び出すとチャットが自動に開始されます。

1
2
3
4
5
6
7
8
9
10
11
12
{
initialize: function() {
function startChat() {
if (window.interpanda.showChat) {
window.interpanda.showChat();
} else {
setTimeout(startChat, 300);
}
}
startChat();
}
}

テンプレートエンジンへのアクセス

render として登録された callback は以下つの引数を取ります。

1
2
3
4
{
render: function(script, template) {
}
}
名前 意味
script スクリプトオブジェクト
template テンプレート関数

例えば、 /scenarios/47/scripts/249 のようなシナリオ47、スクリプト249に以下のようなスクリプトが登録されているとします。

1
2
3
4
5
マッチ度は以下の通りとなります。
1位 {* first_place *}
2位 {* second_place *}
3位 {* third_place *}

{* *}で囲まれた変数は、テンプレート変数として展開されます。
テンプレート変数はユーザーの回答内容だけでなく、 JavaScript APIからも追加することが可能で、具体的には以下のように、
template 関数の引数として渡します。

1
2
3
4
5
6
7
8
9
10
11
12
13
{
render: function(script, template) {
if (script.id == 249) {
var ranking = this.getRanking();
return template({
first_place: ranking[0],
second_place: ranking[1],
third_place: ranking[2]
});
}
return template();
}
}