In an effort to make my code more testable, I'm trying to make use of constructors and prototypes.
Questions:
-
I'd like to be able to write unit tests for both
createAddonMenuandshowSidebar, but at this moment I don't believe it's possible as I'm not returning a value from neither method; I'm simply just calling Google's third party code for creating a menu and showing a sidebar. Would I need to create a wrapper around any code calling a third party's code, and then call that within my method? -
I'd like a sanity check on when I should create a constructor. I feel like maybe I'm trying to shove too many arguments into it, and maybe trying to do too much. Should I create two separate constructors (one for
createMenuand one forshowSidebar)? Should I even be using constructors at all?
Here is a working Google Apps Script (GAS) for creating a new submenu under the Addon main menu in a Google Spreadsheet, and if a user clicks the 'Show' menu item, a sidebar will appear.
var UI = function (menuName, menuFunction, sidebarFile, sidebarTitle) {
this.menuName = menuName;
this.menuFunction = menuFunction;
this.sidebarFile = sidebarFile;
this.sidebarTitle = sidebarTitle;
};
UI.prototype.createAddonMenu = function () {
try {
SpreadsheetApp.getUi()
.createAddonMenu()
.addItem(this.menuName, this.menuFunction)
.addToUi();
Logger.log('onOpen (success): building menu');
} catch (e) {
Logger.log('onOpen (fail): ' + e);
}
};
UI.prototype.showSidebar = function () {
var ui = HtmlService.createTemplateFromFile(this.sidebarFile)
.evaluate()
.setTitle(this.sidebarTitle)
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
return SpreadsheetApp.getUi()
.showSidebar(ui);
};
var ui = new UI('Show', 'showSidebar', 'index', 'Awesome Title');
// onOpen is a built-in Google Apps Script function that gets called when the spreadsheet is opened
function onOpen(e) {
return ui.createAddonMenu();
}
// showSidebar is a standalone function and returns the ui showSidebar method. needs to be this way in order to be called from createAddonMenu
function showSidebar() {
return ui.showSidebar();
}
Aucun commentaire:
Enregistrer un commentaire