建立自訂 ThingWorx 小器具的範例
本部份描述如何建立自訂小器具並在執行時間對其進行處理。
Mashup Builder 程式碼
<widgetname>.ide.js 檔案必須實行小器具函數才能使用 Mashup Builder。如需有關可用於小器具之函數的詳細資訊,請參閱 小器具 API:Mashup Builder 部份。小器具可以在函數中宣告小器具內容、服務和事件。
下列範例程式碼顯示如何建立小器具。小器具的名稱是 MyWidget,其中包含可繫結字串內容 (稱為 DisplayText)。
TW.IDE.Widgets.mywidget = function () {
this.widgetIconUrl = function() {
return "../Common/extensions/MyExtension/ui/" +
"mywidget/mywidget.ide.png";
};
this.widgetProperties = function () {
return {
name : "My Widget",
description : "An example widget.",
category : ["Common"],
properties : {
DisplayText: {
baseType: "STRING",
defaultValue: "Hello, World!",
isBindingTarget: true
}
}
}
};
this.renderHtml = function () {
var mytext = this.getProperty('MyWidget Property');
var config = {
text: mytext
}
var widgetTemplate = _.template(
'<div class="widget-content widget-mywidget">' +
'<span class="DisplayText"><%- text %></span>' +
'</div>'
);
return widgetTemplate(config);
};
this.afterSetProperty = function (name, value) {
return true;
};
};
執行時間程式碼
欲在執行時間處理小器具,必須使用小器具方法執行下列動作:
在執行時間轉譯 HTML
轉譯 HTML 之後,設定繫結
處理內容更新
下列範例程式碼顯示在 Mashup Builder 程式碼中建立之自訂小器具的 <widgetname>.runtime.js 檔案。
TW.Runtime.Widgets.mywidget = function () {
var valueElem;
this.renderHtml = function () {
var mytext = this.getProperty('MyWidget Property');
var config = {
text: mytext
}
var widgetTemplate = _.template(
'<div class="widget-content widget-mywidget">' +
'<span class="DisplayText"><%- text %></span>' +
'</div>'
);
return widgetTemplate(config);
};
this.afterRender = function () {
valueElem = this.jqElement.find(".DisplayText");
valueElem.text(this.getProperty("DisplayText"));
};
this.updateProperty = function (updatePropertyInfo) {
if (updatePropertyInfo.TargetProperty === "DisplayText") {
valueElem.text(updatePropertyInfo.SinglePropertyValue);
this.setProperty("DisplayText",
updatePropertyInfo.SinglePropertyValue);
}
};
};
小器具中可用的其他功能
您可以在小器具中新增下列功能:
服務可以繫結至事件。例如:
按一下按鈕。
所選列已變更。
服務已完成。
事件可以繫結至各種服務。例如,當您呼叫服務時,它會瀏覽至混搭。
小器具內容可以具有:
與其繫結的資料 (輸入)。輸入資料在小器具定義程式碼中指定為 "isBindingTarget": true
傳送回 ThingWorx 的資料 (輸出)。輸出資料在小器具定義程式碼中指定為 "isbindingSource": true
例如,下列範例程式碼中的 user_input_for_name 為使用者輸入,其為輸出資料。
this.widgetProperties = function () {
return {
"name": "user_input_for_name",
"description": "Sample widget that returns a user input",
"category": ['Common'],
"properties": {
"DisplayText": {
"baseType": "STRING",
"defaultValue": "My First Widget!",
"isBindingTarget": true,
"isbindingSource": true
}
}
};
};
您可以在執行時間存取小器具程式碼中之 JavaScript 與 HTML 的所有功能。