I shall use my widget in a lot of place. This would be a final user job to use it like that. So it’s got to be quick and simple job!
And I’d like to know how to do it.
I have a problem in figuring out how widget render in the render
method. I can’t see where and how they insert the html they need to insert into the DOM. As for the execute
method, I have seen how to fetch inside for my widget parameters. I just can’t see how to use them (except for console.log
stuff).
So I have a look at widgets sources again. And I found what I wanted with in TiddlyWiki5/core/modules/widgets/button.js at master · Jermolene/TiddlyWiki5 · GitHub
And I now have a preliminary working code (see below). But a question remains: where is the $ext
widget source code???
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
const Widget = require("$:/core/modules/widgets/widget.js").widget;
let InsertWidget = function(parseTreeNode, options) {
this.initialise(parseTreeNode,options);
};
/*
Inherit from the base widget class
*/
InsertWidget.prototype = new Widget();
InsertWidget.prototype.execute = function() {
this.codeInfo = this.getAttribute("codeInfo", "code");
this.instructions = this.getAttribute("instructions", "what it means");
this.example = this.getAttribute("example","sample");
console.log("codeInfo=", this.codeInfo, "instructions=", this.instructions, "example=", this.example);
}
/*
Render this widget into the DOM
*/
InsertWidget.prototype.render = function(parent, nextSibling) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
console.log("$insert.codeInfo=", this.codeInfo);
const tag = "div";
let node = this.document.createElement(tag);
node.setAttribute("debug", this.codeInfo);
node.setAttribute("onclick", `alert("clicked on ${this.codeInfo}")`);
node.innerHTML = `looking for ${this.codeInfo} (${this.instructions})`;
// Insert element
parent.insertBefore(node, nextSibling);
this.renderChildren(parent, nextSibling);
};
/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
InsertWidget.prototype.refresh = function(changedTiddlers) {
return this.refreshChildren(changedTiddlers);
};
exports.insert = InsertWidget;
})();
Note: I have opted for onclick
instead of addEventListener
. Is that a crime? And should I bother with refresh
?
And also, is the widget built every so often by the render
method? I would have thought of the creation of the DOM bits in a setup method instead of a render method.