These are some notes on JavaScript and programming in general, originally written by MichaelBridgen for 2004's course.\n\n!! Programming languages\n\nA programming language is just a code for doing calculations, like\nmathematical notation. An //interpreter// takes the code as input and\nperforms the calculation. Like mathematical notation, the code has to\nbe concise and unambiguous.\n\nThe set of rules governing the form that the code takes is the\n//syntax//. How the code tells the interpreter to behave is the\n//semantics//. A lot of the difference between programming languages\nis in the syntax, rather than the behaviour.\n\n!! Expressions\n\nAs an example of a calculation, try\n\n{{{\n4 + 5;\n}}}\n\n(the semi-colon at the end signals the end of a calculation). The\nJavaScript interpreter returns the obvious result:\n\n=> //9//\n\nIf you input numbers, the interpreter will treat them as numbers (this\nworks for real numbers as well). You can also enter pieces of text in\nquote marks, like\n\n{{{\n"here is some text"\n}}}\n\n'Adding' strings (of characters) concatenates the pieces of text;\n\n{{{\n"here is " + "some text";\n}}}\n\n=> //"here is some text"//\n\nThere are other operators, like multiplication (an asterisk), division\n'/' and exponentiation '^'. You can use parentheses to enforce\nprecedence, just like in arithmetic:\n\n{{{\n4 * (5 + 2);\n}}}\n\nYou can mix up types of value, and the interpreter will try its best\nto give you a result:\n\n{{{\n"what is the result? " + 4;\n}}}\n\nThe interpreter will usually return //undefined// if it can't\ncalculate what you're asking.\n\n!! Names for things\n\nSo that we don't have calculate an expression more than once, we can\nname the result to be used later on. In JavaScript, the keyword\n''var'' introduces a name for something and the equals sign links\nthe name to the value; e.g.,\n\n{{{\nvar intermediate = 4 + 5;\n}}}\n\nWe can now use the name in the place of the value in later\ncalculations:\n\n{{{\nintermediate * 2;\n}}}\n\n=> //18//\n\n!! Logical expressions\n\nAs well as using arithmetic, JavaScript also has comparison operators\nlike ''<'', ''>'', ''=='' (note the double equals for //comparing// values).\nThe result of a comparison is a ''boolean'' value - ''true'' or\n''false''. So, for instance,\n\n{{{\n"this string" == "this string" ;\n\n"this string" == "that string" ;\n}}}\n\n=> //true//\n\n=> //false//\n\nFor combining boolean values, there are the operators 'AND' (''&&'') and\n'OR' (''||''). With a bit of experimentation we can see how these\nbehave:\n\n{{{\ntrue && true ;\n\ntrue && false ;\n\nfalse && true ;\n\nfalse && false ;\n}}}\n\nSo, the value of an AND expression is true only if both the operands\nare true.\n\nThe value of an OR expression is true if //either// (or both) of the\noperands are true.\n\nWe can use boolean values to make decisions in expressions.\nJavaScript has the ''ternary operator'' for this purpose:\n\n{{{\n( <boolean-expression> ) ? <if-true> : <if-false> ;\n}}}\n\nJavaScript first evaluates boolean-expression; if the result is\n''true'', the value of the entire expression is the value of\nif-true; otherwise, it is the value of if-false. For example,\ndetermining the plurality of a noun:\n\n{{{\n( numberOfMice > 1 ) ? "mice" : "mouse" ;\n}}}\n\n\n!! Procedures\n\nNot only can we name values, but we can name calculations. There is a\nspecial piece of syntax for making a procedure in JavaScript:\n\n{{{\n function ( parameters ) { return result; }\n}}}\n\nWe can give a name to a function:\n\n{{{\n var square = function (x) { return x * x; } ;\n}}}\n\nThe parameters are names that you supply values for when you apply the\nfunction. This function reads as 'a procedure in which, when given\nsome value x, the result is x times x'. The //x// is a placeholder\nfor the value.\n\nNow we can apply the function by supplying a value in the place of the\nparameter //x//:\n\n{{{\n square (6);\n}}}\n\n=> //36//\n\nThe value of a function application such as above is the function\nbody evaluated with the placeholder //x// replaced by the value we\ngave: //6//.\n\nWe can also supply an expression as the value of the parameter:\n\n{{{\n square (4 + 5);\n}}}\n\n=> //81//\n\n!! //Aside//\n\nThere are two ways JavaScript can evaluate //square(4 + 5);//\nFirstly, it could replace every mention of the parameter //x// with\nthe expression given:\n\n//square(4 + 5)//\n\n-> //(4 + 5) * (4 + 5)//\n\n-> //81//\n\nthen evaluate the entire expression; or, it can evaluate the argument,\nthen do the replacement, then evaluate:\n\n//square(4 + 5)//\n\n-> //square(9)//\n\n-> //9 * 9//\n\n-> //81//\n\nThe first is called ''Normal order'' and the second ''Applicative order''.\nJavaScript uses applicative order. The distinction isn't important\nunless, as is the case with JavaScript, it's possible there are side\neffects from evaluating an expression. With normal order, you can see\nthat the expression is effectively evaluated twice, which means any\nside-effects would also happen twice.\n\n!! Scope\n\nYou may have wondered, "what if I've already used 'x' as a name?".\nJavaScript handles this issue by having the notion of 'scope'. Making\na function introduces a scope, whereby the parameter names are\n//local// and only defined inside the function. Variables defined\ninside the function are also //local// to the function.\n\nWhen referring to a name, the name used is the one defined in the\nnearest scope //in the code//. For example, in\n\n{{{\n var x = 8;\n square = function (x) { return x * x; } ;\n square (4);\n}}}\n\n=> //16//\n\nthe x inside the function takes the value of //4//, not //8//,\nwhen //square// is applied to //4//. We can replace 'x' in the\nfunction parameters and body with 'y' and not change the result:\n\n{{{\n var x = 8;\n var square = function (y) { return y * y; };\n square (4);\n}}}\n\n=> //16//\n\n{Write a function called 'abs' that returns the absolute value of a number.}\n\n{{{\nvar abs = function (n) {\n return (n < 0) ? - n : n ;\n} ;\n}}}\n\n{Write a function 'average' that returns the average of two numbers.}\n\n{{{\nvar average = function (n, m) {\n return (n + m)/2 ;\n} ;\n}}}\n\n{Write a function 'max3' that returns the largest of three numbers.}\n\n{{{\nvar max3 = function (x, y, z) {\n return (x > y) ? ((x > z) ? x : z) : (( y > z) ? y : z) ;\n} ;\n}}}\n\n!! Function example\n\nHere I'm going to use the example given in [SICP]: Finding square roots using Newton's Method.\n\nFirst, we'll describe the solution in words, then transcribe it to JavaScript.\n\n1. For a number x, make an initial guess at the square root, y\n2. see how close it is; if close enough, we have our answer\n3. if not close enough, find a better guess by averaging y and x/y\n\nFor a start, we have to define what 'close enough' is. We'll use a tolerance:\n\n{{{\nvar TOLERANCE = 0.0001 ;\nvar closeEnough = function (guess, x) { return (abs(square(guess) - x )) < TOLERANCE ; } ;\n}}}\n\nNow, we encode the procedure for making a better guess:\n\n{{{\nvar betterGuess = function (guess, x) { return average(guess, x / guess) ; } ;\n}}}\n\nand finally, our solution:\n\n{{{\nvar sqrtIter = function (guess, x) {\n return (closeEnough(guess, x)) ?\n guess :\n sqrtIter(betterGuess(guess, x), x) ; } ;\nvar sqrt = function (x) { return sqrtIter(1.0, x); } ;\n}}}\n\n{Using an absolute tolerance doesn't work well with small or very large numbers. Rewrite the functions above so that the "good enough" criterion is that successive guesses are close to each other}\n\nNote that we can define values inside function definitions, so that we can 'hide' the auxiliary procedures inside the definition of //sqrt//; after all, the //sqrt// function is the only one we really care about being available to other functions. Since the //x// is now //in scope//, we don't need to include it as a parameter.\n\n!! Recursion and Iteration\n\nIn the previous examples, the function //sqrtIter// was used in its own definition. This is worth looking at further, but we'll use a more simple example: computing a factorial.\n\nThe factorial of a number //n// is denoted by ''n!'' and is n * (n - 1) '' ... '' 1; that is, the product of all whole numbers between 1 and n. Factorials are used in, among other things, determining permutations and combinations; e.g., calculating the answers to questions like "how many ways can I choose 6 from 40 lottery balls".\n\nThe procedure for generating a factorial is suggested by the definition above, along with observing that 1! is just 1:\n\n{{{\nvar factorial = function(n) { return (n == 1) ? 1 : n * factorial(n-1) ; };\n}}}\n\nAnother way of calculating the factorial is to hold values for the result so far, and the number we are up to, which we increment:\n\n{{{\nvar factorialIter = function(n, res, i) { return (i > n) ? res : factorialIter(n, res * i, i+1) ; } ;\nvar factorial = function(n) { return factorialIter(n, 1, 1) ; } ;\n}}}\n\nThese give the same results, but if we simulate them using our subsitution principle of earlier, we can see that the first 'expands' while it waits for the function applications to be evaluated, whereas the second can evaluate the function arguments straight away.\n\n{The Fibonacci sequence goes 1, 1, 2, 3, 5, 8, ..., (f-1)+(f-2). Write a recursive function to calculate a given member of the sequence}\n\n{Adapt your function to be iterative, if it isn't already}\n\n!! Special forms\n\nThe iterative factorial procedure above holds onto all its state as parameters; at any point, the arguments represent all the information necessary to continue with the calculation. This pattern is so common that JavaScript has special syntax for describing iterative processes.\n\n{{{\nfor (initial ; condition ; update) { ... } ;\ne.g.., for (var i=0; i < 10; i++) { ... } ;\n}}}\n\nHere the variable //i// is initally given the value 0, and the body (...) is repeated, with //i// being incremented each time, until the condition //i < 10// fails. The statements in the body may make use of //i//; our factorial example above becomes\n\n{{{\nvar factorial = function(n) {\n var result = 1;\n for (var i=0 ; i < n ; i++) {\n result = result * i ;\n }\n return result;\n} ;\n}}}\n\nYou can also see that it is possible to change values after they have been defined. In fact, in some programming languages, this is pretty much the only way to get things done!\n\nThere's also a shortcut form for defining functions:\n\n{{{\nfunction <name> ( <parameters> ) { <body> }\n // body can have more than one statement\n}}}\n\nThe longer conditional form is if:\n{{{\nif ( <condition> ) { <true-body> } else { <false-body> }\n // the bodies may be more than one statement\n}}}\n\n!! References\n\n''[SICP]'' Structure and Interpretation of Computer Programming, available online\nat\nhttp://mitpress.mit.edu/sicp/full-text/book/book-Z-H-4.html#%//toc//start\nis an excellent introduction to programming using the language Scheme.\nIn fact, I've adapted most of the content here from the first\nchapter(s) of SICP.\n\n''[NSJS]'' Netscape JavaScript Reference. A sturdy reference for the JavaScript language - after all, Netscape invented it. Found at http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/\n
Stands for "Asynchronous JavaScript and XML". The "asynchronous" part is referring to a style of programming in which the client-side JavaScript in a page makes calls to XML web services in the background, while the user is operating the controls embedded in the page. Answers from the web service can be used to update the [[DOM]] of the page on-the-fly, without needing to reload the entire page, make a complete server round-trip, or prevent the user from continuing her work while communication with the server takes place.\n\nThe basic idea - communicating with the server in the background, and using the results to update the [[DOM]] using [[DHTML]] methods - is of course not restricted to XML. An alternative means of formatting the data travelling to and from the web service (which [[I|TonyGarnockJones]] highly recommend) is [[JSON|http://www.json.org/]].
Stands for "Application Programming Interface" - an API defines the data structures and procedures exposed by a library of code.
<<option chkOpenInNewWindow>> OpenLinksInNewWindow\n<<option chkSaveEmptyTemplate>> SaveEmptyTemplate\n<<option chkToggleLinks>> Clicking on links to tiddlers that are already open causes them to close\n^^(override with Control or other modifier key)^^\n<<option chkHttpReadOnly>> HideEditingFeatures when viewed over HTTP\n<<option chkSaveLexicalOrder>> SaveInLexicalOrder\n
Andy is a director of LShift.\nmailto:andy@lshift.net
A ContentManagementSystem is [...]
Stands for "Dynamic HTML", and is briefly mentioned on the [[W3C DOM standards page|http://www.w3.org/DOM/#why]]. A collection of technologies that allow programmers to create modern animated, responsive user-interfaces using HTML, CSS, and JavaScript's [[DOM]] [[API]].\n\nDHTML user interfaces are starting to rival Flash interfaces in a lot of ways; one of the main remaining weaknesses, the lack of support for vector graphics, is being remedied with browser support for [[SVG|http://www.w3.org/TR/SVG/]].
Stands for "Document Object Model". It's the library that models an HTML document being displayed by a browser, including the actual HTML elements, the CSS stylesheets, and other associated paraphernalia. Sadly, the DOM [[API]] varies from browser to browser, so consulting a guide such as "[[JavaScript: the Definitive Guide|http://www.oreilly.com/catalog/jscript4/]]" is essential. It is best to try to stick to the [[definition of the W3C standard DOM API|http://www.w3.org/DOM/]] where possible - modern browsers (NS6+, IE6+, Safari) stick closely enough to the standard to make it usable for real-world projects.\n\nResources:\n* The DOM in Gecko (the engine powering Mozilla and Firefox): http://www.mozilla.org/docs/dom/domref/\n* Mozilla DOM resources: http://www.mozilla.org/docs/dom/\n* Microsoft's DOM/DHTML reference: http://msdn.microsoft.com/workshop/author/dhtml/reference/dhtml_reference_entry.asp\n
[[Introduction]]\n[[Lecture One]]\n[[Lecture Two]]\n[[Lecture Three]]
GreaseMonkey is a FireFox extension (available from http://greasemonkey.mozdev.org/) which gives users control over the pages they browse to. For instance, there is a GreaseMonkey script that uses [[RegularExpression]]s to search for UK postcodes in the displayed page and hyperlinks the postcodes to the corresponding [[map|http://maps.google.co.uk/]]. The example explored in [[Lecture Three]] was a revamping of the JavaScript console example into a dynamic addendum to each page viewed in the browser, which is useful for debugging and reverse-engineering of [[DHTML]] pages in the wild.
This is a TiddlyWiki instance that TonyGarnockJones of LShift set up for the KeepingWebsitesAlive course at UWestminster, 2005.\n\nIn here, we compare and contrast various kinds of ContentManagementSystem, including TiddlyWiki (of which this document is an instance), WordPress, and [[Zope]].\n\nWe also provide a brief introduction to JavaScript and related ideas and technologies.
JavaScript is the programming language behind the [[DHTML]] effects seen on the Web today.\n* [[2004 JavaScript Notes]] by MichaelBridgen\n* AndyWilson's JavaScript notes are available at http://www.andyw.com/westminster/\n* On the [[DOM]] page are some links to JavaScript and DOM documentation and resources.\n\nJavaScript is an [[ECMA|http://www.ecma-international.org/]] standardised language, [[ECMA-262, available here|http://www.ecma-international.org/publications/standards/Ecma-262.htm]].\n\nThere are some great JavaScriptLibraries being used in modern [[DHTML]] user interfaces, using JavaScript for animation effects and responsive client-server user interfaces.
Some libraries used to augment basic JavaScript are:\n* [[prototype.js|http://prototype.conio.net/]], a library that makes object-oriented programming in JavaScript more convenient, and offers a number of handy utilities for working with the [[DOM]] (such as the almost //essential// definition of the $() function).\n* [[script.aculo.us|http://script.aculo.us/]], a library building on prototype.js that implements a number of animations as well as solid [[AJAX]] support.\n* [[Rico|http://openrico.org/rico/home.page]], a library that also builds on prototype.js and is broadly similar to script.aculo.us\n\nAn interesting library is [[behaviour.js|http://bennolan.com/behaviour/]], which allows you to //declaratively// associate JavaScript code with your HTML elements without needing to alter your HTML at all (other than adding CSS classes to elements). The CSS classes of the HTML elements in your documents are matched against CSS selectors, and when a match is found, the element is customised with JavaScript event handlers on-the-fly.
From http://www.lshift.net/:\n\n"LShift is a pure technology company with experience of developing complex solutions for large companies.\n\n"Our sole aim is to deliver the most suitable technology for your business. We don't just look at the technical brief, we look at the overall solution. We achieve our high standards by hiring only the best & most experienced people in the industry.\n\n"In short, LShift will offer you a speed and quality of technical solution you won't be able to find elsewhere."
In which [[ContentManagementSystem]]s were discussed, TiddlyWiki, WordPress and [[Zope]] were introduced, and the notion of ModelViewController was espoused as a sensible way of designing software.
In which more JavaScript and DHTML examples and exercises were worked through, further investigation of JavaScriptLibraries and [[AJAX]] was undertaken, GreaseMonkey was installed and briefly explored, and [[RegularExpression]]s and [[CssSelector]]s were introduced.\n\nLinks:\n* The JavaScript programming assignment that we constructed variations upon: http://nifty.stanford.edu/2004/TalkLikeAPirate/\n* The Structure and Interpretation of Computer Programs, the ultimate coursebook covering the foundations of computer programming - once you read the first one or two chapters of this book, you will have a framework for understanding any programming language you encounter: [[Full text of SICP online!|http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-4.html#%_toc_start]] - don't be put off by the seeming complexity, it really is a very accessible book. The software used for all the examples is open-source and freely-available: http://download.plt-scheme.org/drscheme/\n* A few notes on JavaScript's implementation of the RegularExpression pattern-matching system: http://www.koralsoft.com/regextester/jssyntax.html\n* The (very clear and readable) specification of CSS2 Selectors: http://www.w3.org/TR/REC-CSS2/selector.html\n
In which JavaScript and [[DHTML]] were introduced, some experimentation with the [[DOM]] and related [[API]]s was done, some demonstration of various JavaScriptLibraries was given, a presentation on LShift's [[Expro]] ContentManagementSystem was given by StuartMottram, and some of the basics of programming languages were touched upon.
\n[[Introduction]]\n\nTiddlyWiki\nWordPress\n[[Zope]]\n\nJavaScript\n[[DHTML]]\n[[DOM]]\n\nContent © 2005 LShift.net\n\n<<newTiddler>>\n
Michael works for LShift.\nmailto:mikeb@lshift.net
[[RegularExpression]]s are used for matching patterns in text. The language used to describe a RegularExpression is a DomainSpecificLanguage for text pattern matching. Example uses include:\n* validating email addresses\n* simple text parsing tasks, such as splitting out the components of a string representing a date (e.g. "2005/09/25", when matched against the perl regular expression "(\sd{4})/(\sd{2})/(\sd{2})" gives the three groups "2005", "09" and "25")\n* converting WikiWiki markup to HTML\n\nThe following links provide some introduction to regular expressions:\n* http://en.wikipedia.org/wiki/Regular_expression - WikiPedia as usual provides a good overview and some history\n* http://www.webreference.com/js/column5/index.html - a comprehensive introduction and tutorial specifically about using regular expressions in JavaScript\n* http://www.regexlib.com/DisplayPatterns.aspx - a collection of handy regex patterns submitted by users of the site; includes utility regexes for email validation, date/time parsing, etc.\n* http://sitescooper.org/tao_regexps.html - covers the use of regular expressions in a few common Unix command-line utilities\n\nThe mathematics of regular expressions is interesting: it stretches from the Chomsky hierarchy of languages at one end, through finite- and infinite-state automatons, all the way to symbolic differentiation of patterns at the other!\n\nHere's a JavaScript RegularExpression example you can try out using a JavaScript console utility of some kind. I've only tested it in FireFox - IE and Safari users' [[mileage may vary|http://www.catb.org/~esr/jargon/html/Y/Your-mileage-may-vary.html]].\n\n{{{\n/\sd+\ss+\sw+\ss+\sd{4}/.exec("23 Sep 2005")\n}}}\n\n--> {{{["23 Sep 2005"]}}}\n\nThis defines a regular expression {{{/\sd+\ss+\sw+\ss+\sd{4}/}}}, which matches:\n* one-or-more ''d''igits, followed by\n* one-or-more ''s''paces, followed by\n* one-or-more characters that could occur in a ''w''ord, followed by\n* one-or-more ''s''paces, followed by\n* exactly four ''d''igits.\n\nAfter defining the regular expression, the {{{.exec}}} method is called on it, passing in the string to match against the regular expression. The result of the {{{.exec}}} call is either {{{null}}} (if the string passed in didn't match the regex) or an array of length one containing only the matching substring of the argument. To see a successful match, try evaluating the example above; and for a failed match, see what happens when you evaluate the following example:\n\n{{{\n/\sd+\ss+\sw+\ss+\sd{4}/.exec("2005 Sep 23")\n}}}\n\n--> {{{null}}}\n\nIt's important to note that a regular expression will extract a matching value from within a longer string - try this example:\n\n{{{\n/\sd+\ss+\sw+\ss+\sd{4}/.exec("It all began on the afternoon of 23 Sep 2005, as I was walking through the park.")\n}}}\n\n--> {{{["23 Sep 2005"]}}}\n\nThe {{{^}}} and {{{$}}} operators are used to force the expression to match the entire string - see one of the reference sites linked to above.\n\nFinally, we'll modify the example so that it splits the date into its components.\n\n{{{\n/(\sd+)\ss+(\sw+)\ss+(\sd{4})/.exec("23 Sep 2005")\n}}}\n\n--> {{{["23 Sep 2005","23","Sep","2005"]}}}\n\nNote the difference: we've placed parentheses ('(', ')') around the sections of the pattern we wish to group together. Note that the answer that JavaScript gives for this expression is different, too: instead of a length-one array containing a simple string, we now get a //longer// array of strings, containing an extra entry for each set of parentheses in the regular expression. Entry number 0 is the entire matched substring; and entries 1 through 3 correspond in order to the parenthesised groups in the regular expression.
// Make the order of tiddlers when saved a configurable option\n\nconfig.options.chkSaveLexicalOrder = true;\nloadOptionsCookie();\n\nfunction allTiddlersAsHtml()\n{\n var savedTiddlers = [];\n var orderBy = (config.options.chkSaveLexicalOrder) ? "title" : "modified";\n var tiddlers = store.getTiddlers(orderBy);\n for (var t = 0; t < tiddlers.length; t++)\n savedTiddlers.push(tiddlers[t].saveToDiv());\n return savedTiddlers.join("\sn");\n}\n
notes on [[ContentManagementSystem]]s
KeepingWebsitesAlive
http://www.tiddlywiki.com/
Stuart is a director of LShift.\nmailto:stuart@lshift.net
TiddlyWiki is a complete JavaScript client-side implementation of a WikiWiki. It uses divs in the HTML page to store the WikiMarkup, and JavaScript routines to render the WikiMarkup to HTML code on the fly. Changes are only kept locally: to save changes, make a local copy of the file, view it in your browser, and use the save functionality built-in to TiddlyWiki.\n\nFor more information, see http://www.tiddlywiki.com/.\n
Tony works for LShift.\nmailto:tonyg@lshift.net
WordPress (http://wordpress.org/) is a powerful and easy-to-use (once it's installed) blogging program. LShift uses it for their [[company blog|http://www.lshift.net/blog/]]. It's implemented in PHP, using MySQL as the database.
Zope (http://www.zope.org/) is a CMS and web development framework implemented using [[Python|http://www.python.org/]]. Its basic model is a hierarchy (mapping direcly to URL paths) of objects.