Unknown macro in library - google-apps-script

I am trying to make a library, went well so far, but after adding a few functions it went bad.
When I run the script form the editor it is written in the script works. But when I try to test it the script cannot recognize the server handlers, giving an error: Unknown macro handler_function_name
I checked, all the names in the handlers correspond to names of functions. I read that some people had problems because the code was in different files, moved all the code in the same file the problem is still there.
It does not behave like that for all the handlers...
What else could be the reason for this?
edit:
The app creates additional panels during as a response to "clicks". Handlers of elements on those panels are the ones who's macros (that is handler functions) the app is not able to "find".
How can this be solved?
(except for the solution to put all the panels in the original panel and then change visibility, this works as far as handlers go but raises other problems)
So to put some code here, this is very very simple code...
function notWorkingGUI(){
var app=UiApp.createApplication();
var appPanel=app.createVerticalPanel().setId("appPanel");
var handler1=app.createServerHandler("handlerFunction1").addCallbackElement(appPanel);
var firstButton=app.createButton("Button 1", handler1);
appPanel.add(firstButton);
app.add(appPanel);
SpreadsheetApp.getActive().show(app);
}
function handlerFunction1(e){
var app=UiApp.getActiveApplication();
var appPanel2=app.createVerticalPanel().setId("appPanel2").setStyleAttribute("zIndex", 0).setStyleAttribute("position", "fixed");
var handler2=app.createServerHandler("handlerFunction2").addCallbackElement(appPanel2);
var secondButton=app.createButton("Button 2", handler2);
var label=app.createLabel("This should get visible after the click").setId("label").setVisible(false);
appPanel2.add(secondButton).add(label);
app.add(appPanel2);
return app;
}
function handlerFunction2(e){
var app=UiApp.getActiveApplication();
app.getElementById("label").setVisible(true);
return app;
}
This will work as expected when executed from the editor in which it is written, that is it will show firstButton then secondButton and finaly the label, however if it would be published as a library and invoked from an other script it would only recognise functionHandler1, that is show firstButton, secondButton but after a click on the secondButton an error message will be seen.
However if the script would be written like this:
function workingGUI(){
//previous first part
var app=UiApp.createApplication();
var appPanel=app.createVerticalPanel().setId("appPanel");
var handler1=app.createServerHandler("handlerFunction1a").addCallbackElement(appPanel);
var firstButton=app.createButton("Button 1", handler1);
//previous second part
var appPanel2=app.createVerticalPanel().setId("appPanel2").setStyleAttribute("zIndex", 0).setStyleAttribute("position", "fixed");
var handler2=app.createServerHandler("handlerFunction2a").addCallbackElement(appPanel2);
var secondButton=app.createButton("Button 2", handler2).setId("button2");
appPanel.add(firstButton);
app.add(appPanel);
SpreadsheetApp.getActive().show(app);
}
function handlerFunction1a(e){
var app=UiApp.getActiveApplication();
var label=app.createLabel("This should get visible after the click").setId("label").setVisible(false);
app.getElementById("appPanel2").add(app.getElementById("button2")).add(label);
app.add(app.getElementById("appPanel2"));
return app;
}
function handlerFunction2a(e){
var app=UiApp.getActiveApplication();
app.getElementById("label").setVisible(true);
return app;
}
Note that all handlers must be defined in the main function, meaning that also all the elements using those handlers and all the callback elements have to be defined here.
Then it would work even as a library, however for some reason this makes the script much much slower even for such a simple example.

The issue is here:
http://code.google.com/p/google-apps-script-issues/issues/detail?id=1346
It is calling the local code rather than the library code.
I wonder if it is still slow if you add a stub function in the local code?
i.e.
function runthis() {
library.createGUI();
}
function myevent() {
library.myevent();
}

I worked around this problem, it makes the script a bit slower but if you define all the handlers (that implies all the UI elements) in the original function it will work.

Related

How can I relaunch/update/refresh the card again using Apps Script

I'm having a nightmare doing a lot of scenarios using Apps Script, but nothing works! I have a function that makes a GET request returns an array of cards. Now, sometimes I need this card refreshes again to fetch the new content.
function listTemplatesCards(){
var getAllTemplates = getTemplates();
var allTemplates = getAllTemplates.templates;
var theUserSlug = getAllTemplates.user_slug;
var templateCards = [];
//There are templates
if(allTemplates.length > 0){
allTemplates.forEach(function(template){
templateCards.push(templateCard(template, theUserSlug).build());
});
return templateCards;
}
}
This function is called on onTriggerFunction. Now, if I moved to another card and I wanted to back again to the root but in clean and clear way, I use this but it doesn't work:
//Move the user to the root card again
var refreshNav = CardService.newNavigation().popToRoot();
return CardService.newActionResponseBuilder().setStateChanged(true).setNavigation(refreshNav).build();
Simply, what I want is once the user clicks on Refresh button, the card refreshes/updates itself to make the call again and get the new data.
The only way I've found to do this is to always use a single card for the root. In the main function (named in the appscript.json onTriggerFunction), return only a single card, not an array of cards. You can then use popToRoot().updateCard(...) and it works.
I struggled with this for over a day, improving on Glen Little's answer so that its a bit more clear.
I have my root card to be refreshed defined in a funciton called: onHomepage.
I update the appscript.json manifest to set the homepageTrigger and onTriggerFunction to return the function that builds my root card.
"gmail": {
"homepageTrigger": {
"enabled": true,
"runFunction":"onHomepage"
},
"contextualTriggers":[
{
"unconditional":{},
"onTriggerFunction": "onHomepage"
}
]
}
Then it is as simple as building a gotoRoot nav button function that will always refresh the root page.
function gotoRootCard() {
var nav = CardService.newNavigation()
.popToRoot()
.updateCard(onHomepage());
return CardService.newActionResponseBuilder()
.setNavigation(nav)
.build();
}
As far as gmail addons are considered, cards are not refreshed but updated with new cards. And it is pretty simple.
//lets assume you need a form to be updated
function updateProfile() {
//ajax calls
//...
//recreate the card again.
var card = CardService.newCardBuilder();
//fill it with widgets
//....
//replace the current outdated card with the newly created card.
return CardService.newNavigation().updateCard(card.build());
}
A bad hack that works for my Gmail add-on:
return CardService.newActionResponseBuilder()
.setStateChanged(true) // this doesn't seem to do much. Wish it would reload the add-on
.setNotification(CardService.newNotification()
.setText('Created calendar event')
)
// HACK! Open a URL which closes itself in order to activate the RELOAD_ADD_ON side-effect
.setOpenLink(CardService.newOpenLink()
.setUrl("https://some_site.com/close_yoself.html")
.setOnClose(CardService.OnClose.RELOAD_ADD_ON))
.build();
The contents of close_yoself.html is just:
<!DOCTYPE html>
<html><body onload="self.close()"></body></html>
So, it looks like Google has considered and solved this issue for an ActionResponse which uses OpenLink, but not for one using Navigation or Notification. The hack above is definitely not great as it briefly opens and closes a browser window, but at least it refreshes the add-on without the user having to do so manually.

Error with custom Search and Replace function for Google Sites

I'm trying to use a script to replace a particular string with a different string. I think the code is right, but I keep getting the error "Object does not allow properties to be added or changed."
Does anyone know what could be going wrong?
function searchAndReplace() {
var teams = SitesApp.getPageByUrl("https://sites.google.com/a/directory/teams");
var list = teams.getChildren();
list.forEach(function(element){
page = element.getChildren();
});
page.forEach(function(element) {
var html = element.getHtmlContent();
html.replace(/foo/, 'bar');
element.setHtmlContent = html;
});
};
Try This:
Javascript reference:
The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.
I think the issue here is that forEach cannot change the array that it is called upon. From developer.mozilla.org "forEach() does not mutate the array on which it is called (although callback, if invoked, may do so)."
Try doing it with a regular loop.

uiInstance.close() has no effect

I have the following code inside a script for a Google Spreadsheet:
var uiInstance;
function displayDialog() {
uiInstance = UiApp.createApplication()
.setWidth(130)
.setHeight(130);
uiInstance.add(uiInstance.createLabel("foo"));
SpreadsheetApp.getUi().showModalDialog(uiInstance, 'bar');
}
This dialog is intended to inform the user the script is calculating something and I want to close the dialog again once the script has finished its work. If I use
uiInstance.close();
inside or outside the function nothing seems to happen though; the dialog remains opened until the user closes it. Is there any solution for my problem?
you have to "return" to effectively close the uiInstance, return is needed to reflect any change you made to the Ui, including closing it.
try
return uiInstance.close();
EDIT following your comment :
UiApp instances can only be closed from a handler function, I thought that was how you were using it (but I might have been wrong).
Below is a small code example :
function displayDialog() {
var uiInstance = UiApp.createApplication()
.setWidth(130)
.setHeight(130);
uiInstance.add(uiInstance.createLabel("foo"));
var handler = uiInstance.createServerHandler('closeDialog');
uiInstance.add(uiInstance.createButton('close',handler));
SpreadsheetApp.getUi().showModalDialog(uiInstance, 'bar');
}
function closeDialog(){
return UiApp.getActiveApplication().close();
}
There is also a tricky workaround that can "simulate" a user action. It uses a property of some widgets to trigger a handler function when they change value. In the example below I used a checkBox to start the process
It will close the dialog when the task in doStuf is done.
function displayDialog() {
var uiInstance = UiApp.createApplication()
.setWidth(130)
.setHeight(130);
uiInstance.add(uiInstance.createLabel("foo"));
var handler = uiInstance.createServerHandler('doStuf');
var chk = uiInstance.createCheckBox().setValue(true).setId('chk').setVisible(false);
chk.addValueChangeHandler(handler);
uiInstance.add(chk);
chk.setValue(false,true)// This actually calls the doStuf function (using the handler)
SpreadsheetApp.getUi().showModalDialog(uiInstance, 'bar');
}
function doStuf(){
Utilities.sleep(5000);// replace with something useful ...
return UiApp.getActiveApplication().close();
}
Use:
uiInstance = uiInstance.close();
SpreadsheetApp.getUi().showModalDialog(uiInstance, 'bar');

HTML is not updated when using Mootools dragging

I'm using Mootools (don't think it is related to the problem) to drag and drop and element.
var draggable = new Drag(timeHandle, {
onDrag: function () {
var calculatedTime = calcTime();
$('timeLabel').innerHTML = calculatedTime;
},
});
Basically, I can drag my 'timeHandle' and the 'timeLabel' is getting updated properly.
The problem is that sometimes, after moving the handle a little bit, suddently, the UI is not getting updated. The 'timeHandle' is not moving and the 'timeLabel' is not getting updted.
The problem is not with the drag event, I can see it keeps on getting called.
When I move
$('timeLabel').innerHTML = calculatedTime;
everything works fine.
So, the problem is not with the 'Drag' object since the event is kept on calling.
Looks like some UI performance issue.
Thanks
To simplify your code, you can use Element.set('text', 'my text here');
var element = $('timeLabel');
var draggable = new Drag(timeHandle, {
onDrag: function () {
element.set('text', calcTime());
}
});
Also, remember to remove that last comma or it will throw errors in Internet Explorer.
OK, found a to make it work.
I still not sure what caused the problem but it looks like the 'innerHTML' command has either really poor performance which causes problems in the GUI updates or maybe some kind of internal mechanism (IE only? which is supposed to prevent the UI from updates overflow.
Anyway, instead of using the innerHTML, I'm doing the following:
var draggable = new Drag(timeHandle, {
onDrag: function () {
var calculatedTime = calcTime();
var element = $('timeLabel');
element.removeChild(element.firstChild);l
element.appendChild(element.ownerDocument.createTextNode(calculatedTime));
},
});
Works like a charm

WinJS variable/object scope, settings, and events?

I am not sure what the proper heading / title for this question should be. I am new to WinJS and am coming from a .NET webform and winclient background.
Here is my scenario. I have a navigation WinJS application. My structure is:
default.html
(navigation controller)
(settings flyout)
pages/Home.html
pages/Page2.html
So at the top of the default.js file, it sets the following variables:
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
var nav = WinJS.Navigation;
It seems like I cannot use these variables anywhere inside my settings flyout or any of my pages:ready functions. They are only scoped to the default.js?
In the same regard, are there resources on the interwebs (links) that show how to properly share variables, events, and data between each of my "pages"?
The scenario that I immediately need to overcome is settings. In my settings flyout, I read and allow the user to optionally set the following application setting:
var applicationData = Windows.Storage.ApplicationData.current;
var localSettings = applicationData.localSettings;
localSettings.values["appLocation"] = {string set by the user};
I want to respond to that event in either my default.js file or even one of my navigation pages but I don't know where to "listen". My gut is to listen for the afterhide event but how do I scope that back to the page where I want to listen from?
Bryan. codefoster here. If you move the lines you mentioned...
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
var nav = WinJS.Navigation;
...up and out of the immediate function, they'll be in global scope and you'll have access to them everywhere. That's one of the first things I do in my apps. You'll hear warnings about using global scope, but what people are trying to avoid is the pattern of dropping everything in global scope. As long as you control what you put in there, you're fine.
So put them before the beginning of the immediate function on default.js...
//stuff here is scoped globally
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
var nav = WinJS.Navigation;
(function () {
//stuff here is scoped to this file only
})();
If you are saving some data and only need it in memory, you can just hang it off the app variable instead of saving it into local storage. That will make it available to the whole app.
//on Page2.js
app.myCustomVariable = "some value";
//on Page3.js
if(app.myCustomVariable == "some value") ...
Regarding your immediate need:
like mentioned in the other answer, you can use datachanged event.
Regards sharing variables:
If there are variables that you would like to keep global to the application, they can be placed outside the anonymous function like mentioned in the Jeremy answer. Typically, that is done in default.js. Need to ensure that scripts using the global variables are placed after the script defining the global variable - in default.html. Typically - such variable will point to singleton class. For example: I use it in one of my apps to store authclient/serviceclient for the backend service for the app. That way - the view models of the multiple pages need not create instance of the object or reference it under WinJS namespace.
WinJS has also concept of Namespace which lets you organize your functions and classes. Example:
WinJS.Namespace.define('Utils.Http',
{
stringifyParameters: function stringifyParameters(parameters)
{
var result = '';
for (var parameterName in parameters)
{
result += encodeURIComponent(parameterName) + '=' + encodeURIComponent(parameters[parameterName]) + '&';
}
if (result.length > 0)
{
result = result.substr(0, result.length - 1);
}
return result;
},
}
When navigating to a page using WinJS.Navigation.navigate, second argument initialState is available as options parameter to the ready event handler for the page. This would be recommended way to pass arguments to the page unless this it is application data or session state. Application data/session state needs to be handled separately and needs a separate discussion on its own. Application navigation history is persisted by the winjs library; it ensures that if the app is launched again after suspension - options will be passed again to the page when navigated. It is good to keep the properties in options object as simple primitive types.
Regards events:
Typically, apps consume events from winjs library. That can be done by registering the event handler using addEventListener or setting event properties like onclick etc. on the element. Event handlers are typically registered in the ready event handler for the page.
If you are writing your own custom control or sometimes in your view model, you may have to expose custom events. Winjs.UI.DOMEventMixin, WinJS.Utilities.createEventProperties can be mixed with your class using WinJS.Class.mix. Example:
WinJS.Class.mix(MyViewModel,
WinJS.Utilities.createEventProperties('customEvent'),
WinJS.UI.DOMEventMixin);
Most often used is binding to make your view model - observable. Refer the respective samples and api documentation for details. Example:
WinJS.Class.mix(MyViewModel,
WinJS.Binding.mixin,
WinJS.Binding.expandProperties({ items: '' }));
Here is what I ended up doing which is kinda of a combination of all the answers given:
Created a ViewModel.Settings.js file:
(function () {
"use strict";
WinJS.Namespace.define("ViewModel", {
Setting: WinJS.Binding.as({
Name: '',
Value: ''
}),
SettingsList: new WinJS.Binding.List(),
});
})();
Added that file to my default.html (navigation container page)
<script src="/js/VMs/ViewModel.Settings.js"></script>
Add the following to set the defaults and start 'listening' for changes
//add some fake settings (defaults on app load)
ViewModel.SettingsList.push({
Name: "favorite-color",
Value: "red"
});
// listen for events
var vm = ViewModel.SettingsList;
vm.oniteminserted = function (e) {
console.log("item added");
}
vm.onitemmutated = function (e) {
console.log("item mutated");
}
vm.onitemchanged = function (e) {
console.log("item changed");
}
vm.onitemremoved = function (e) {
console.log("item removed");
}
Then, within my application (pages) or my settings page, I can cause the settings events to be fired:
// thie fires the oniteminserted
ViewModel.SettingsList.push({
Name: "favorite-sport",
Value: "Baseball"
});
// this fires the itemmutated event
ViewModel.SettingsList.getAt(0).Value = "yellow";
ViewModel.SettingsList.notifyMutated(0);
// this fires the itemchanged event
ViewModel.SettingsList.setAt(0, {
Name: "favorite-color",
Value: "blue"
});
// this fires the itemremoved event
ViewModel.SettingsList.pop(); // removes the last item
When you change data that needs to be updated in real time, call applicationData.signalDataChanged(). Then in the places that care about getting change notifications, listen to the datachanged on the applicationData object. This is also the event that is raised when roaming settings are synchronized between computers.
I've found that many times, an instant notification (raised event) is unnecessary, though. I just query the setting again when the value is needed (in ready for example).