Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use global variables in event handlers
    text
    copied!<p>I have a global variable contacts, <em>var contacts = ContactsApp.getContacts();</em></p> <p>I have an KeyUphandler for my textbox called search(). </p> <p>In search(), contacts[0].getPrimaryEmail() gives out an error, "<strong>Cant call method getPrimaryEmail of undefined</strong>" </p> <p>However contacts[0].getPrimaryEmail() works fine in other normal functions. </p> <p>Cant we use global variables in event handlers?</p> <p>The code is given below,</p> <p>//CODE starts</p> <pre><code> var contacts = ContactsApp.getContacts(); function ShowAuto() { var app = UiApp.createApplication().setTitle('Simple Autocomplete'); var Panel = app.createVerticalPanel().setId('mainPanel').setWidth('555px'); var textBox = app.createTextBox().setName('textBox').setWidth('330px').setId('textBox'); var tBoxHandler = app.createServerKeyHandler('search'); tBoxHandler.addCallbackElement(textBox); textBox.addKeyUpHandler(tBoxHandler); var listBox = app.createListBox().setName('list').setWidth("330px").setId('list').setVisibleItemCount(5) .setStyleAttribute("border", "1px solid white") .setStyleAttribute("background", "white").setVisible(false); Panel.add(app.createLabel().setId('label')); Panel.add(textBox); Panel.add(listBox); app.add(Panel); var ownerEmail = Session.getActiveUser().getEmail(); // I used this method first.. It din work. // var contacts = ContactsApp.getContacts(); // for (var i in contacts) // { // var emailStr = contacts[i].getPrimaryEmail(); // conts[i]=emailStr; // Browser.msgBox(emailStr); // } //These two calls are just to test, the contacts Array, They work fine :) getContact(0); getContact(1); var ss = SpreadsheetApp.getActiveSpreadsheet(); ss.show(app); } function getContact(n) { // Browser.msgBox(contacts[n].getPrimaryEmail()); Logger.log(contacts[n].getPrimaryEmail()); //works fine return contacts[n].getPrimaryEmail(); } function search(e) { var app = UiApp.getActiveApplication(); //Logger.log(contacts[0].getPrimaryEmail()); //Not working app.getElementById('label').setText(e.parameter.textBox.toString()); // app.getElementById('label').setText(conts[0]); app.getElementById('list').setVisible(true); var searchKey = new RegExp(e.parameter.textBox.toString(),"gi"); if (searchKey == "") app.getElementById('textBox').setValue(''); var listBoxCount = 0; for (i=0;i&lt;5;i++){ //Here is where i get error if(contacts[i].indexOf(e.parameter.textBox)!=-1 &amp;&amp; listBoxCount &lt; 5) { app.getElementById('list').addItem(conts[i]); listBoxCount++; } } } </code></pre> <p>Sorry if i was unclear </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload