Contenu connexe
Similaire à AD114 - Don't be afraid of curly brackets reloaded - even more JavaScript for LotusScript Developers (20)
AD114 - Don't be afraid of curly brackets reloaded - even more JavaScript for LotusScript Developers
- 1. 1609 #
Don't be afraid of curly brackets reloaded
even more JavaScript for LotusScript Developers
Stephan H. Wissel | NotesSensei | IBM
© 2012 IBM Corporation
- 2. 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.
2 | © 2012 IBM Corporation
- 3. Agenda
■ JavaScript the Basics*
■ Writing good JavaScript
■ Server Side JavaScript – what you never knew you wanted to ask
* Pun intended
3 | © 2012 IBM Corporation
- 4. 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
4 | © 2012 IBM Corporation
- 5. 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
5 | © 2012 IBM Corporation
- 7. JavaScript - a child of many parents
* SSJS uses Java RegEx
7 | © 2012 IBM Corporation
- 8. 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
8 | © 2012 IBM Corporation
- 9. 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)
9 | © 2012 IBM Corporation
- 16. 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
16 | © 2012 IBM Corporation
- 18. 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”;
18 | © 2012 IBM Corporation
- 28. 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
28 | © 2012 IBM Corporation
- 29. First Class Functions
function sayHello() {
return “Hello World”
}
var x = sayHello; → x() → “Say Hello”
var y = sayHello(); → y() → undefined
x → function
y → “Say Hello”
var m = new Function("x", "y", "return x * y");
29 | © 2012 IBM Corporation
- 30. 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”;
30 | © 2012 IBM Corporation
- 31. JavaScript – reserved words
■ Now: ■ Then:
break, case, catch, continue, default, abstract, boolean, byte, char, class,
delete, do, else, finally, for, function, const, debugger, double, enum,
if, in, instanceof, new, return, switch, export, extends, final, float, goto,
this, throw, try, typeof, var, void, implements, import, int, interface,
while, with long, native, package, private,
protected, public, short, static, super,
synchronized, throws, transient,
volatile
■ Also:
null, true, false,
const, export, import
31 | © 2012 IBM Corporation
- 32. 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,
32 | © 2012 IBM Corporation
- 33. 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: 33 | © 2012 IBM Corporation
- 34. 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
34 | © 2012 IBM Corporation
- 35. JavaScript syntax constructs
■ if (exp) { … } ■ try { … }
else if (exp2) { … } catch ( errorObject ) { … }
else { … } finally { … }
■ switch (exp) { ■ x++ y--;
case v1 : ...; break; ■ x += y;
case v2 : ...; break;
default; ■ x={}
} ■ // rest of the line comment
■ for (start;condition;loop) { … } ■ /* Inline to multi-line comment */
■ for (var propName in object) { … } ■ /** Java(Script)Doc comment **/
■ while (condition) { … }
■ do { … } while (condition)
■ with (object) { … }
35 | © 2012 IBM Corporation
- 36. 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
36 | © 2012 IBM Corporation
- 37. The Object Model
■ Depends on the container
■ Browser
● window (default)
● navigator For browser use the regular DOM
● screen and out of the box functions
● history
is not good enough for successful
web2.0 applications!
● location
● document (HTML DOM) Use a framework like dojo or jQuery
■ XPages (server side) to improve developer productivity
and user experience.
● database
● session Comes with a learning curve!
● params
● context
● … more later
37 | © 2012 IBM Corporation
- 38. Agenda
■ JavaScript the Basics
■ Writing good JavaScript
■ Server Side JavaScript – what you never knew you wanted to ask
38 | © 2012 IBM Corporation
- 40. Wouldn't it be nice
if somewhere real
JavaScript could be
found to learn!
40 | © 2012 IBM Corporation
- 41. 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
41 | © 2012 IBM Corporation
- 42. 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
42 | © 2012 IBM Corporation
- 43. Take an online class!
■ http://www.codecademy.com/subjects/javascript
43 | © 2012 IBM Corporation
- 44. 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
44 | © 2012 IBM Corporation
- 46. 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 46 | © 2012 IBM Corporation
- 47. 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
47 | © 2012 IBM Corporation
- 49. Agenda
■ JavaScript the Basics
■ Writing good JavaScript
■ Server Side JavaScript – what you never knew you wanted to ask
49 | © 2012 IBM Corporation
- 50. 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
50 | © 2012 IBM Corporation
- 51. 51 | © 2012 IBM Corporation
- 52. Thank you!
FILL IN YOUR SESSION
EVALUATIONS*
52 | © 2012 IBM Corporation
* or a kitten must die!
- 54. Your favorite constructs
■ Good reference:
http://www-
10.lotus.com/ldd/ddwiki.nsf/dx/NotesDocument_sample_JavaScript_code_for_
XPages
■ More code:
http://www.xpageswiki.com/web/youatnotes/wiki-xpages.nsf/xpViewTags.xsp?
categoryFilter=javascript
54 | © 2012 IBM Corporation
- 55. Basic error handling
■ LotusScript SS JavaScript
■
Function MyCoolFunction function myCoolFunction() {
Dim … var ...
On Error Goto Err_MyCoolFunction try {
.... .....
} catch (e) {
Exit_MyCoolFunction: alert(e.message); // ← That's lousy
'Cleanup code // Error handling here
...
Exit Function } finally {
// Cleanup code
Err_MyCoolFunction: ....
Call logError '← You use OpenLog or? }
'Error handling here
… }
Resume Exit_MyCoolFunction
End Function
55 | © 2012 IBM Corporation
- 56. Process all selected documents
■ LotusScript ■ SS JavaScript
Dim s as new NotesSession var vPanel = getComponent(“viewPanel1”);
Dim db as NotesDatabase var docids = vPanel.getSelectedIds();
Dim dcol as NotesDocumentCollection for (var curId in docids) {
Dim doc as NotesDocument doSomethingWithTheDocId(curId)
Dim nextDoc as NotesDocument }
--------
Set db = s.currentDatabase function doSomethingWithTheDocId(id) {
Set dcol = db.UnprocessedDocuments var doc:NotesDocument =
Set doc = dcol.getFirstDocument database.getDocumentById(id);
// Do what has to be done
Do until doc is Nothing // ...
Set nextDoc = dcol.getNextDocument(doc) doc.recycle();
Call DoSomethingWithTheDoc(doc) }
Set doc = nextDoc
Loop
56 | © 2012 IBM Corporation
- 57. Process submitted document
■ LotusScript ■ SS JavaScript
Dim s as new NotesSession
Dim doc as NotesDocument 2 Options:
- XSP Object
Set doc = s.documentContext - Notes Object
'Do what you have to do
Call doc.replaceItemValue(“x”,”y”)
doc.test = “test” var xDoc = currentDocument; // XSP
var doc = xDoc.getDocument(); // Java
//Do what you have to do
xDoc.replaceItemValue(“x”,”y”);
doc.replaceItemValue(“test”,”test”);
doc.recycle();
57 | © 2012 IBM Corporation
- 58. Get URL parameters
http://myServer/myNSF.nsf/[someIdentifier]?Open&color=red&Status=Open&beer=Tiger
■ LotusScript ■ SS JavaScript
Dim s as New NotesSession
Dim doc as NotesDocument context.getUrlParameter(“color”)
Dim qString as String context.getUrlParameter(“Status”)
Dim qValues as Variant context.getUrlParameter(“beer”)
Set doc = s.documentContext facesContext.getExternalContext().getR
equest().getQueryString();
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=”))
58 | © 2012 IBM Corporation
- 59. Dim x LIST as String
■ LotusScript ■ SS JavaScript
Dim x LIST as String var x;
x(“divorce1”) = “Ken's house” x[“divorce1”] = “Ken's house”;
x(“divorce2”) = “Ken's car” x[“divorce2”] = “Ken's car”;
x(“divorce3”) = “Ken's boat” x[“divorce3”] = “Ken's boat”;
IsMember(x(“divorce4”)) → False x[“divorceTotal”] = 3000000.0;
Erase x(“divorce3”) x[“divorce4”] → undefined / false
Erase x x.divorce3 = undefined;
x = undefined;
59 | © 2012 IBM Corporation
- 60. Work with MIME*
■ LotusScript ■ SS JavaScript
Dim s as new NotesSession var body =
Dim doc as NotesDocument getComponent(“Body”).getValue();
Dim body as NotesMimeEntry
s.ConvertMIME = false
Set doc = s.documentContext
Set body = doc.getMIMEEntry(“Body”)
* Speak after me: “The web knows no RichText, it's a ghost of Christmas past”
60 | © 2012 IBM Corporation
- 61. Script Libraries (Code reuse)
■Lotus Script ■ JavaScript
Use “MyLibrary” <xp:script src="/mylib.jss"
clientSide="false"></xp:script>
Dim someGlobal as String // Do not define global variables here
Dim anotherGlobal as NotesDocument
Dim oneMoreGlobal as NotesView if (!viewScope.myGlobals) {
viewScope.myGlobals = {
“someGlobal” = “World Peace”,
Function doSomething as Integer “anotherGlobal” = “”,
if someGlobal = “World Domination” then “oneMoreGlobal” = “viewName”}
Call SupermanNeedsToFixThis }
end if }
doSomething = 42
End function function doSomething() {
if (viewScope.myGlobals.someGlobal
== “Word Domination”) {
supermanNeedsToFixThis()
Don't use Notes Backend classes }
outside the requestScope! return 42;
}
61 | © 2012 IBM Corporation
- 62. 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 = {}
}
}
62 | © 2012 IBM Corporation
- 63. 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);
63 | © 2012 IBM Corporation
- 64. 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/
64 | © 2012 IBM Corporation
- 65. 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.
65 | © 2012 IBM Corporation