AD114 - Don't be afraid of curly brackets reloaded - even more JavaScript for LotusScript...

Preview:

DESCRIPTION

Introduction into JavaScript for LotusScript developers. Focus on the language, not the XPages objects.

Citation preview

© 2012 IBM Corporation

1609 # Don't be afraid of curly brackets reloadedeven more JavaScript for LotusScript Developers

Stephan H. Wissel | NotesSensei | IBM

2 | © 2012 IBM Corporation

IBM’s statements regarding its plans, directions, and intent are subject to change or withdrawal without notice at IBM’s sole discretion.

Information regarding potential future products is intended to outline our general product direction and it should not be relied on in making a purchasing decision.

The information mentioned regarding potential future products is not a commitment, promise, or legal obligation to deliver any material, code or functionality. Information about potential future products may not be incorporated into any contract. The development, release, and timing of any future features or functionality described for our products remains at our sole discretion.

3 | © 2012 IBM Corporation

Agenda■ JavaScript the Basics*

■ Writing good JavaScript

■ Server Side JavaScript – what you never knew you wanted to ask

* Pun intended

4 | © 2012 IBM Corporation

About Me

■ IBM Collaboration & Productivity Advisor■ Counsellor for personcentric development■ IBM Singapore Pte Ltd■ Blog: http://www.wissel.net/■ Twitter: notessensei■ Google: http://www.wissel.net/+■ Lotus Notes since 2.1

■ Favorite motorbike: Moto Guzzi Le Mans■ Speaks Singlish with a German accent

5 | © 2012 IBM Corporation

About You*

■ Develop software(or need to know about it)

■ Have a LotusScript background(or heard about it)

■ Want to develop XPages(or let develop)

■ Are new to JavaScript(or feel new)

■ Just are a fan(welcome back)

* 2 out of 5 qualify you

6 | © 2012 IBM Corporation

Java[What]?

7 | © 2012 IBM Corporation

JavaScript - a child of many parents

* SSJS uses Java RegEx

8 | © 2012 IBM Corporation

ECMA-262 (ISO/IEC 16262)

JavaScript is an implementation of the ECMAScript language standard and is typically used to enable programmatic access to computational objects within a host environment. It can be characterized as a prototype-based object-oriented scripting language that is dynamic, weakly typed and has first-class functions. It is also considered a functional programming language [...] because it has closures and supports higher-order functions.

Source http://en.wikipedia.org/wiki/JavaScript

9 | © 2012 IBM Corporation

Host Environment

■ Browsers● Firefox: Spidermonkey, Tracemonkey● Chrome: V8● IE: Chakra (IE9)● Safari: Nitro● Opera: Carakan

■ Flash: ActionScript (Tamarin)■ Servers

● ColdFusion● Mozilla Rhino● IBM Websphere sMash (a.k.a Project ZERO)● IBM Xpages● Node.js

■ OS Level● Windows Scripting Host● Jrunscript (install the JDK6)

10 | © 2012 IBM Corporation

JavaScript Command line*

jrunscriptecho(“Hello World”);

*You need a JDK6 for that

11 | © 2012 IBM Corporation

Step by Step...

12 | © 2012 IBM Corporation

JavaScript Language Basics

cAsE

13 | © 2012 IBM Corporation

JavaScript Language Basics

var x;

14 | © 2012 IBM Corporation

JavaScript Language Basics

var x;http://inimino.org/~inimino/blog/javascript_semicolons

15 | © 2012 IBM Corporation

JavaScript Language Basics

[“red”,”blue”]

16 | © 2012 IBM Corporation

JavaScript Language Basics

var y = new Array();var y = [“red”,”blue”];y[y.length] = “new Value”; //Appends a value /* Same same, but can take more than one parameter */

y.push(“new Value”);y.pop(); //Get one back on the end (LIFO)y.shift(); // Same same but FIFO

JS Arrays ~= LotusScript Lists

17 | © 2012 IBM Corporation

JavaScript Language Basics

{ };

18 | © 2012 IBM Corporation

The power of {}

var x = new Object();var x = {};x.answerToAllQuestions = 42;x[“WhoSaidThat”] = “Douglas Adams”;var result = x.WhoSaidThat + “ said “ + x[“answerToAllQuestions”];alert(result); → “Douglas Adams said 42”;

19 | © 2012 IBM Corporation

JavaScript Language Basics

a=ba==ba===b

assign

compare “loosely”

compare “strict”

20 | © 2012 IBM Corporation

JavaScript Language Basics

name() {...};

21 | © 2012 IBM Corporation

JavaScript Language Basics

arguments

22 | © 2012 IBM Corporation

JavaScript Language Basics

arguments.length;arguments[0];arguments.callee;

23 | © 2012 IBM Corporation

JavaScript Language Basics

X = if ? true : false;

24 | © 2012 IBM Corporation

JavaScript Language Basics

X = Y || “default”;

25 | © 2012 IBM Corporation

JavaScript Language Basics

\” \'

26 | © 2012 IBM Corporation

JavaScript Language Basics

// /* */

27 | © 2012 IBM Corporation

JavaScript Language Basics

eval(“some String”);

28 | © 2012 IBM Corporation

First Class Functions

■ In computer science, a programming language is said to support first-class functions [...] if it treats functions as first-class objects. Specifically, this means that the language supports constructing new functions during the execution of a program, storing them in data structures, passing them as arguments to other functions, and returning them as the values of other functions.

Source: http://en.wikipedia.org/wiki/First-class_function

29 | © 2012 IBM Corporation

First Class Functions

function sayHello() { return “Hello World”}var x = sayHello; → x() → “Say Hello”var y = sayHello(); → y() → undefinedx → functiony → “Say Hello”var m = new Function("x", "y", "return x * y");

30 | © 2012 IBM Corporation

Higher Order Functions

function HelloWorld() {

“sayHello” : function(whoAreYou) {

return “Hello “+whoAreYou+”, nice to meet you”

},

“getHello” : function() {

return this.sayHello;

}

}

var x = HelloWorld.getHello();

x(“Peter”) → “Hello Peter, nice to meet you”;

31 | © 2012 IBM Corporation

JavaScript – reserved words

■ Now:break, case, catch, continue, default, delete, do, else, finally, for, function, if, in, instanceof, new, return, switch, this, throw, try, typeof, var, void, while, with

■ Also:null, true, false,const, export, import

■ Then:abstract, boolean, byte, char, class, const, debugger, double, enum, export, extends, final, float, goto, implements, import, int, interface, long, native, package, private, protected, public, short, static, super, synchronized, throws, transient, volatile

32 | © 2012 IBM Corporation

LotusScript reserved words (refresher) 1/2

■ %Else, %ElseIf, %End, %If, %Include, %REM, ACos, ASin, Abs, Access, ActivateApp, Alias, And, Any, AppActivate, Append, ArrayAppend, ArrayGetIndex, ArrayReplace, ArrayUnique, As, Asc, Atn, Atn2, Base, Beep, Bin, Bin$, Binary, Bind, Boolean, ByVal, Byte, CBool, CByte, CCur, CDat, CDbl, CInt, CLng, CSng, CStr, CVDate, CVar, Call, Case, ChDir, ChDrive, Chr, Chr$, Close, CodeLock, CodeLockCheck, CodeUnlock, Command, Command$, Compare, Const, Cos, CreateLock, CurDir, CurDir$, CurDrive, CurDrive$, Currency, DataType, Date, Date$, DateNumber, DateSerial, DateValue, Day, Declare, DefBool, DefByte, DefCur, DefDbl, DefInt, DefLng, DefSng, DefStr, DefVar, Delete, DestroyLock, Dim, Dir, Dir$, Do, DoEvents, Double, EOF, Else, ElseIf, End, Environ, Environ$, Eqv, Erase, Erl, Err, Error, Error$, Evaluate, Event, Execute, Exit, Exp, Explicit, FALSE, FileAttr, FileCopy, FileDateTime, FileLen, Fix, For, ForAll, Format, Format$, Fraction, FreeFile, From, FullTrim, Function, Get, GetAttr, GetFileAttr, GetThreadInfo, GoSub, GoTo, Hex, Hex$, Hour, IMESetMode, IMEStatus, If, Imp, Implode, Implode$, In, InStr, InStrB, InStrBP, InStrC, Input, Input$, InputB, InputB$, InputBP, InputBP$, InputBox, InputBox$, Int, Integer, Is, IsA, IsArray, IsDate, IsElement, IsEmpty, IsList, IsNull, IsNumeric, IsObject, IsScalar, IsUnknown, Join, Kill, LBound, LCase,

33 | © 2012 IBM Corporation

LotusScript reserved words (refresher) 2/2

■ LCase$, LMBCS, LOC, LOF, LSI_Info, LSServer, LSet, LTrim, LTrim$, Left, Left$, LeftB, LeftB, LeftBP, LeftBP$, LeftC, LeftC$, Len, LenB, LenBP, LenC, Let, Lib, Like, Line, List, ListTag, Lock, Log, Long, Loop, Me, MessageBox, Mid, Mid$, MidB, MidB$, MidBP, MidBP$, MidC, MidC$, Minute, MkDir, Mod, Month, MsgBox, NOTHING, NULL, Name, New, Next, NoCase, NoPitch, Not, Now, Oct, Oct$, On, Open, Option, Or, Output, PI, Pitch, Preserve, Print, Private, Property, Public, Published, Put, RSet, RTrim, RTrim$, Random, Randomize, ReDim, Read, Rem, Remove, Replace, Reset, Resume, Return, Right, Right$, RightB, RightB$, RightBP, RightBP$, RightC, RightC$, RmDir, Rnd, Round, Second, Seek, Select, SendKeys, Set, SetAttr, SetFileAttr, Sgn, Shared, Shell, Sin, Single, Sleep, Space, Space$, Spc, Split, Sqr, Static, Step, Stop, Str, Str$, StrComp, StrCompare, StrConv, StrLeft, StrLeft$, StrLeftBack, StrLeftBack$, StrRight, StrRight$, StrRightBack, StrRightBack$, StrToken, StrToken$, String, String$, Sub, TRUE, Tab, Tan, Text, Then, Time, Time$, TimeNumber, TimeSerial, TimeValue, Timer, To, Today, Trim, Trim$, Type, TypeName, UBound, UCase, UCase$, UChr, UChr$, UString, UString$, Uni, Unicode, Unlock, Until, Use, UseLSX, Val, VarType, Variant, Weekday, Wend, While, Width, With, Write, Xor, Year, Yield

Source:

34 | © 2012 IBM Corporation

JavaScript data types & build in functions

■ String → “Hello World”■ Number → 42.0■ boolean → true|false■ undefined → new variables■ null → empty values

● null == undefined → true● null === undefined → false

■ new Date()■ new Array() → []■ new Error(“S..t happens”) // Error.message to retrieve■ Regular expressions (but that's a story for another time!)

More here: http://en.wikipedia.org/wiki/ECMAScript_syntax

35 | © 2012 IBM Corporation

JavaScript syntax constructs

■ if (exp) { … }else if (exp2) { … }else { … }

■ switch (exp) { case v1 : ...; break; case v2 : ...; break; default; }

■ for (start;condition;loop) { … }■ for (var propName in object) { … }■ while (condition) { … }■ do { … } while (condition)■ with (object) { … }

■ try { … }catch ( errorObject ) { … }finally { … }

■ x++ y--;■ x += y;■ x = { }■ // rest of the line comment■ /* Inline to multi-line comment */■ /** Java(Script)Doc comment **/

36 | © 2012 IBM Corporation

Serializing JavaScript : JSON

var whatIsLotusNotes = {

“database” : [“document”, “objectstore”], “creator” : “Ray Ozzie”, “platforms” : [”linux”, “zlinux”, ”mac”, ”solaris”, ”aix”, ”iOS”,“windows”], “released” : 1989, “getNews” : function() { window.location = “http://www.planetlotus.org/” }, “getSoftware” : function {

return [“http://www.openntf.org/”, “http://www.notesappstore.com/”, “http://itunes.apple.com/us/app/ibm-lotus-notes-traveler-companion”] } // ← Last member no comma!

}

JSON = Cross platform / Cross language object serialization

37 | © 2012 IBM Corporation

The Object Model

■ Depends on the container■ Browser

● window (default)● navigator● screen● history● location● document (HTML DOM)

■ XPages (server side)● database● session● params● context● … more later

For browser use the regular DOMand out of the box functionsis not good enough for successfulweb2.0 applications!

Use a framework like dojo or jQueryto improve developer productivityand user experience.

Comes with a learning curve!

38 | © 2012 IBM Corporation

Agenda■ JavaScript the Basics

■ Writing good JavaScript

■ Server Side JavaScript – what you never knew you wanted to ask

39 | © 2012 IBM Corporation

Tons of JavaScript examples on the web!

40 | © 2012 IBM Corporation

Wouldn't it be niceif somewhere realJavaScript could befound to learn!

41 | © 2012 IBM Corporation

Learning resources (online)

http://eloquentjavascript.net■ Created by Marijn Haverbeke■ Interactive HTML book, free■ Focus on csJS

http://bonsaiden.github.com/JavaScript-Garden■ Ivo Wetzel, Zhang Yi Jiang■ Good closure explanation■ The case for “Don't use eval”

http://www.w3schools.com/js/■ Popular tutorial site■ Focus on csJS

http://dochub.io/#javascript/■ Online JS reference

42 | © 2012 IBM Corporation

Writing nice JavaScript

■ http://www.jshint.com/■ http://www.javascriptlint.com/■ http://www.jslint.com/

Watch & read these:■ http://www.youtube.com/watch?v=hQVTIJBZook■ http://www.slideshare.net/rmurphey/dojoconf-building-

large-apps

43 | © 2012 IBM Corporation

Take an online class!

■ http://www.codecademy.com/subjects/javascript

44 | © 2012 IBM Corporation

Learning resources (offline)*■ Pro JavaScript Techniques

http://www.apress.com/9781590597279■ Pro JavaScript Design Patterns

http://www.apress.com/9781590599082■ JavaScript The Good Parts

http://shop.oreilly.com/product/9780596517748.do■ JavaScript Patterns

http://shop.oreilly.com/product/9780596806767.do■ JavaScript The Definite Guide

http://shop.oreilly.com/product/9780596805531.do

*I consider eBooks offline too

45 | © 2012 IBM Corporation

ServerSide JavaScript (in XPages)

ECMA Script 262 with a twist...

46 | © 2012 IBM Corporation

ServerSide JavaScript (in XPages)

■ function @runfaster(){...};■ var firstName:string = “Joe”;■ var firstName:com.acme.myClass

= new com.acme.myClass(“Joe”);■ var x = new java.util.LinkedList();■ synchronized(scope*) {…}■ Regex & Date = Java compatible■ .recycle()**

*requestScope, viewScope, sessionScope, applicationScope** When you use Domino Java objects

47 | © 2012 IBM Corporation

ServerSide JavaScript (in XPages)

■ Global functions● getComponent(“id”), getClientId(“id”)● getForm(), getView()● save()● toJson(JsonObject) → String● fromJson(“String looking like JSON”) → Object● isJson(“String looking like JSON”) → true/false

■ Object Model● scope: applicationScope, sessionScope, viewScope, requestScope● cookie● view (That's the JSF View, not a Notes view)● session, sessionAsSigner, sessionAsSignerWithFullAccess,

sessionHandoverYourFirstbornNow● header, headerValues● param, paramValues, initParam● context, faceContext● database

48 | © 2012 IBM Corporation

JavaScript Functions using power constructors

49 | © 2012 IBM Corporation

Agenda■ JavaScript the Basics

■ Writing good JavaScript

■ Server Side JavaScript – what you never knew you wanted to ask

50 | © 2012 IBM Corporation

DEMO: SSJS beyond your LotusScript Universe*

■ Output client side JS using SSJS■ Use scopes to manage parameters■ Combine static and dynamic SSJS computation■ Use of script libraries■ Dynamically modify JavaScript in events■ Object parameters■ Debugging

* You are looking at potential blog posts or Notesin9 sessions

51 | © 2012 IBM Corporation

52 | © 2012 IBM Corporation

Thank you!

FILL IN YOUR SESSIONEVALUATIONS*

* or a kitten must die!

© 2012 IBM Corporation

Appendix – more stuff

55 | © 2012 IBM Corporation

Basic error handling

■ LotusScript

Function MyCoolFunction Dim …

On Error Goto Err_MyCoolFunction ....

Exit_MyCoolFunction: 'Cleanup code ...Exit Function

Err_MyCoolFunction: Call logError '← You use OpenLog or? 'Error handling here … Resume Exit_MyCoolFunctionEnd Function

■ SS JavaScript

function myCoolFunction() { var ... try { ..... } catch (e) { alert(e.message); // ← That's lousy // Error handling here

} finally {

// Cleanup code

.... }

}

56 | © 2012 IBM Corporation

Process all selected documents

■ LotusScript

Dim s as new NotesSessionDim db as NotesDatabaseDim dcol as NotesDocumentCollectionDim doc as NotesDocumentDim nextDoc as NotesDocument

Set db = s.currentDatabaseSet dcol = db.UnprocessedDocumentsSet doc = dcol.getFirstDocument

Do until doc is Nothing Set nextDoc = dcol.getNextDocument(doc) Call DoSomethingWithTheDoc(doc) Set doc = nextDocLoop

■ SS JavaScript

var vPanel = getComponent(“viewPanel1”);var docids = vPanel.getSelectedIds();for (var curId in docids) { doSomethingWithTheDocId(curId)}--------function doSomethingWithTheDocId(id) { var doc:NotesDocument = database.getDocumentById(id); // Do what has to be done // ... doc.recycle(); }

57 | © 2012 IBM Corporation

Process submitted document

■ LotusScript

Dim s as new NotesSessionDim doc as NotesDocument

Set doc = s.documentContext

'Do what you have to doCall doc.replaceItemValue(“x”,”y”)doc.test = “test”

■ SS JavaScript

2 Options:- XSP Object- Notes Object

var xDoc = currentDocument; // XSPvar doc = xDoc.getDocument(); // Java

//Do what you have to doxDoc.replaceItemValue(“x”,”y”);

doc.replaceItemValue(“test”,”test”);

doc.recycle();

58 | © 2012 IBM Corporation

Get URL parameters

■ LotusScript

Dim s as New NotesSessionDim doc as NotesDocumentDim qString as StringDim qValues as Variant

Set doc = s.documentContext

qString = doc.getItemValue(“query_string_decoded”)(0)qValues = split(qString,“&”)

Right$(qValues(1),instr(qValues(1),”color=”))Right$(qValues(2),instr(qValues(2),”Status=”))Right$(qValues(3),instr(qValues(3),”beer=”))

■ SS JavaScript

context.getUrlParameter(“color”)context.getUrlParameter(“Status”)context.getUrlParameter(“beer”)

facesContext.getExternalContext().getRequest().getQueryString();

http://myServer/myNSF.nsf/[someIdentifier]?Open&color=red&Status=Open&beer=Tiger

59 | © 2012 IBM Corporation

Dim x LIST as String

■ LotusScript

Dim x LIST as String

x(“divorce1”) = “Ken's house”x(“divorce2”) = “Ken's car”x(“divorce3”) = “Ken's boat”

IsMember(x(“divorce4”)) → False

Erase x(“divorce3”)

Erase x

■ SS JavaScript

var x;

x[“divorce1”] = “Ken's house”;x[“divorce2”] = “Ken's car”;x[“divorce3”] = “Ken's boat”;

x[“divorceTotal”] = 3000000.0;

x[“divorce4”] → undefined / false

x.divorce3 = undefined;

x = undefined;

60 | © 2012 IBM Corporation

Work with MIME*

■ LotusScript

Dim s as new NotesSessionDim doc as NotesDocumentDim body as NotesMimeEntry

s.ConvertMIME = falseSet doc = s.documentContextSet body = doc.getMIMEEntry(“Body”)

■ SS JavaScript

var body = getComponent(“Body”).getValue();

* Speak after me: “The web knows no RichText, it's a ghost of Christmas past”

61 | © 2012 IBM Corporation

Script Libraries (Code reuse)

■ Lotus Script

Use “MyLibrary”

Dim someGlobal as StringDim anotherGlobal as NotesDocumentDim oneMoreGlobal as NotesView

Function doSomething as Integer if someGlobal = “World Domination” then Call SupermanNeedsToFixThis

end ifdoSomething = 42

End function

■ JavaScript

<xp:script src="/mylib.jss" clientSide="false"></xp:script>

// Do not define global variables here

if (!viewScope.myGlobals) { viewScope.myGlobals = { “someGlobal” = “World Peace”, “anotherGlobal” = “”, “oneMoreGlobal” = “viewName”} }}

function doSomething() {

if (viewScope.myGlobals.someGlobal == “Word Domination”) { supermanNeedsToFixThis() }return 42;}

Don't use Notes Backend classesoutside the requestScope!

62 | © 2012 IBM Corporation

Application Parameter Management

var setup = {

“getColors” : function() { checkCache(); if (applicationScope.appCache.colors == undefined) { applicationScope.appCache.colors = @DbLookup(....); } return applicationScope.appCache.colors },

“getDepartments” : function() { .... },

“checkCache” : function() { if (applicationScope.appCache == undefined) { applicationScope.appCache = {} }

}

63 | © 2012 IBM Corporation

Dynamically modify JavaScript in events

var allData:java.util.List = view.getData();

var myData:com.ibm.xsp.model.domino.DominoDocumentData = allData(0);

var theApplication:javax.faces.application.Application = facesContext.getApplication();

var myListenerFunction:string = "#{javascript:print(\”my Listener called\”)}";

var myListener:javax.faces.el.MethodBinding = theApplication.createMethodBinding(myListenerFunction, null);

myData.setQuerySaveDocument(myListener);

64 | © 2012 IBM Corporation

Additional Readings

■ https://developer.mozilla.org/en/JavaScript/Reference■ http://xpageswiki.com/■ http://www.mozilla.org/rhino/■ http://www.w3schools.com/js/default.asp■ http://www-

10.lotus.com/ldd/ddwiki.nsf/dx/NotesDocument_sample_JavaScript_code_for_XPages

■ http://jibbering.com/faq/notes/closures/■ http://www.json.org/

65 | © 2012 IBM Corporation

Legal disclaimer© IBM Corporation 2012. All Rights Reserved.

The information contained in this publication is provided for informational purposes only. While efforts were made to verify the completeness and accuracy of the information contained in this publication, it is provided AS IS without warranty of any kind, express or implied. In addition, this information is based on IBM’s current product plans and strategy, which are subject to change by IBM without notice. IBM shall not be responsible for any damages arising out of the use of, or otherwise related to, this publication or any other materials. Nothing contained in this publication is intended to, nor shall have the effect of, creating any warranties or representations from IBM or its suppliers or licensors, or altering the terms and conditions of the applicable license agreement governing the use of IBM software.

References in this presentation to IBM products, programs, or services do not imply that they will be available in all countries in which IBM operates. Product release dates and/or capabilities referenced in this presentation may change at any time at IBM’s sole discretion based on market opportunities or other factors, and are not intended to be a commitment to future product or feature availability in any way. Nothing contained in these materials is intended to, nor shall have the effect of, stating or implying that any activities undertaken by you will result in any specific sales, revenue growth or other results.

Performance is based on measurements and projections using standard IBM benchmarks in a controlled environment. The actual throughput or performance that any user will experience will vary depending upon many factors, including considerations such as the amount of multiprogramming in the user's job stream, the I/O configuration, the storage configuration, and the workload processed. Therefore, no assurance can be given that an individual user will achieve results similar to those stated here.

All customer examples described are presented as illustrations of how those customers have used IBM products and the results they may have achieved. Actual environmental costs and performance characteristics may vary by customer.

IBM, the IBM logo, Lotus, Lotus Notes, Notes, Domino, Quickr, Sametime, WebSphere, UC2, PartnerWorld and Lotusphere are trademarks of International Business Machines Corporation in the United States, other countries, or both. Unyte is a trademark of WebDialogs, Inc., in the United States, other countries, or both.Adobe, the Adobe logo, PostScript, and the PostScript logo are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States, and/or other countries.

Java and all Java-based trademarks are trademarks of Oracle Inc. in the United States, other countries, or both.

Microsoft and Windows are trademarks of Microsoft Corporation in the United States, other countries, or both.

Intel, Intel Centrino, Celeron, Intel Xeon, Intel SpeedStep, Itanium, and Pentium are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States and other countries.

UNIX is a registered trademark of The Open Group in the United States and other countries.

Linux is a registered trademark of Linus Torvalds in the United States, other countries, or both. Other company, product, or service names may be trademarks or service marks of others.

All references to fictitious company refer to a fictitious company and are used for illustration purposes only.

Recommended