### doSimpleXMLHttpRequest example: GET with query string Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Async.html Performs a GET request to 'http://example.com?bar=baz' using doSimpleXMLHttpRequest. The query string is built from the extra arguments. ```javascript doSimpleXMLHttpRequest("http://example.com", {bar: "baz"}); ``` -------------------------------- ### partial example: create a partially applied function Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Base.html Shows how to use partial to create a new function with one argument pre-filled. The example defines addNumbers, then creates addOne that adds 1 to its argument. ```javascript addNumbers = function (a, b) { return a + b; } addOne = partial(addNumbers, 1); assert(addOne(2) == 3); ``` -------------------------------- ### loadJSONDoc example with query arguments Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Async.html Shows how to call loadJSONDoc with a URL and query arguments. The function appends a '?' and the queryString result to the URL, performing a GET request to the specified URL. ```javascript loadJSONDoc("http://example.com", {bar: "baz"}); ``` -------------------------------- ### Connect to Draggables 'start' signal Source: https://mochi.github.io/mochikit/doc/html/MochiKit/DragAndDrop.html Registers a callback for the 'start' signal emitted by draggables. The callback receives the draggable object as an argument. This example is from the Draggable constructor documentation. ```javascript onStart = function (draggable) { // Do some stuff }; connect(Draggables, 'start', onStart); ``` -------------------------------- ### withWindow example Source: https://mochi.github.io/mochikit/doc/html/MochiKit/DOM.html Shows how to create DOM nodes in a child window using withWindow and currentDocument. withWindow also implies withDocument. ```javascript withWindow(child, function () { var doc = currentDocument(); appendChildNodes(doc.body, H1(null, "This is in the child!")); }); ``` -------------------------------- ### findValue usage example Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Base.html Shows how to use findValue to locate the index of a value in an array, with optional start index. The first assert checks the first occurrence, the second checks from index 2. ```javascript assert( findValue([1, 2, 3, 2, 1], 2) == 1 ) assert( findValue([1, 2, 3, 2, 1], 2, 2) == 3 ) ``` -------------------------------- ### createDOM table example Source: https://mochi.github.io/mochikit/doc/html/MochiKit/DOM.html Builds a table with head, foot, and body rows using createDOM, map, and partial. The resulting HTML is shown in the following block. ```javascript var rows = [ ["dataA1", "dataA2", "dataA3"], ["dataB1", "dataB2", "dataB3"] ]; row_display = function (row) { return TR(null, map(partial(TD, null), row)); } var newTable = TABLE({'class': 'prettytable'}, THEAD(null, row_display(["head1", "head2", "head3"])), TFOOT(null, row_display(["foot1", "foot2", "foot3"])), TBODY(null, map(row_display, rows))); ``` ```html
head1 head2 head3
foot1 foot2 foot3
dataA1 dataA2 dataA3
dataB1 dataB2 dataB3
``` -------------------------------- ### MochiKit.Base synopsis example Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Base.html Demonstrates core MochiKit.Base features: custom repr, sorting with keyComparator, mapping with itemgetter, and JSON serialization with serializeJSON/evalJSON. Uses assert and compare to verify results. ```javascript myObjectRepr = function () { // gives a nice, stable string representation for objects, // ignoring any methods var keyValuePairs = []; for (var k in this) { var v = this[k]; if (typeof(v) != 'function') { keyValuePairs.push([k, v]); } }; keyValuePairs.sort(compare); return "{" + map( function (pair) { return map(repr, pair).join(":"); }, keyValuePairs ).join(", ") + "}"; }; // repr() will look for objects that have a repr method myObjectArray = [ {"a": 3, "b": 2, "repr": myObjectRepr}, {"a": 1, "b": 2, "repr": myObjectRepr} ]; // sort it by the "a" property, check to see if it matches myObjectArray.sort(keyComparator("a")); expectedRepr = '[{"a": 1, "b": 2}, {"a": 3, "b": 2}]'; assert( repr(myObjectArray) == expectedRepr ); // get just the "a" values out into an array sortedAValues = map(itemgetter("a"), myObjectArray); assert( compare(sortedAValues, [1, 3]) == 0 ); // serialize an array as JSON, unserialize it, expect something equivalent myArray = [1, 2, "3", null, undefined]; assert( objEqual(evalJSON(serializeJSON(myArray)), myArray) ); ``` -------------------------------- ### Synopsis: Load JSON and handle callbacks Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Async.html Shows how to use loadJSONDoc to fetch a JSON file and attach success and error callbacks with addCallbacks. The example checks the version and alerts the user accordingly. ```javascript var url = "/src/b/bo/bob/MochiKit.Async/META.json"; /* META.json looks something like this: {"name": "MochiKit", "version": "0.5"} */ var d = loadJSONDoc(url); var gotMetadata = function (meta) { if (MochiKit.Async.VERSION == meta.version) { alert("You have the newest MochiKit.Async!"); } else { alert("MochiKit.Async " + meta.version + " is available, upgrade!"); } }; var metadataFetchFailed = function (err) { alert("The metadata for MochiKit.Async could not be fetched :("); }; d.addCallbacks(gotMetadata, metadataFetchFailed); ``` -------------------------------- ### Deferred callback sequence example Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Async.html Shows how to add callbacks and errbacks to a Deferred instance. The sequence is internally represented as a list of 2-tuples. ```javascript var d = new Deferred(); d.addCallback(myCallback); d.addErrback(myErrback); d.addBoth(myBoth); d.addCallbacks(myCallback, myErrback); ``` -------------------------------- ### startsWith(substr, str) Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Text.html Checks if the string str starts with the substring substr. Returns a boolean. ```APIDOC ## startsWith(substr, str) ### Description Checks if the string str starts with the substring substr. Returns a boolean. ### Method startsWith ### Parameters - **substr** (string) - Required - The substring to check for at the start. - **str** (string) - Required - The string to check. ### Returns - **boolean** - True if str starts with substr, false otherwise. ### Example ``` assert( startsWith("ab", "abcd") ); ``` ``` -------------------------------- ### elementPosition relativeTo example Source: https://mochi.github.io/mochikit/doc/html/MochiKit/DOM.html Shows how to compute the relative position of an element by subtracting another element's position using elementPosition. The example asserts that the relative coordinates equal the difference of the absolute positions. ```javascript var elemPos = elementPosition(elem); var anotherElemPos = elementPosition(anotherElem); var relPos = elementPosition(elem, anotherElem); assert( relPos.x == (elemPos.x - anotherElemPos.x) ); assert( relPos.y == (elemPos.y - anotherElemPos.y) ); ``` -------------------------------- ### Create a sortable list with MochiKit.Sortable Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Sortable.html Example showing how to create a drag-and-drop sortable list by passing the element ID to Sortable.create. The HTML defines a UL list, and the script initializes it as sortable. ```html ``` -------------------------------- ### URL encoding with urlEncode Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Base.html Example assertion showing that urlEncode converts spaces to %20 instead of '+'. The example checks that URLencode("1+2=2") equals "1%2B2%3D2". ```javascript assert( URLencode("1+2=2") == "1%2B2%3D2"); ``` -------------------------------- ### Synopsis: Positioning and Sizing an Element Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Style.html Shows how to get an element's position and dimensions, create a new Coordinates object, and set the position of another element relative to it. ```javascript var messagePos = getElementPosition('message'); var messageSize = getElementDimensions('message'); var notifyPos = new MochiKit.Style.Coordinates( messagePos.x + messageSize.w + 10, messagePos.y); setElementPosition('notify', notifyPos); ``` -------------------------------- ### Using $$ with MochiKit.Visual.fade Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Selector.html Selects all elements with class 'fademe' using the $$ function and applies the MochiKit.Visual.fade effect to each. This is the synopsis example for the module. ```javascript MochiKit.Base.map(MochiKit.Visual.fade, $$('p.fademe')); ``` -------------------------------- ### toRGBString example Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Color.html Asserts that whiteColor().toRGBString() returns 'rgb(255,255,255)'. Note that if alpha is not 1.0, the output uses 'rgba(red, green, blue, alpha)' format. ```javascript assert( Color.whiteColor().toRGBString() == "rgb(255,255,255)" ); ``` -------------------------------- ### queryString example: build query string from arrays Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Base.html Creates a URL query string from names and values arrays. Values are URL-encoded and pairs with null or undefined values are skipped. ```javascript var keys = ["foo", "bar"]; var values = ["value one", "two"]; assert( queryString(keys, values) == "foo=value%20one&bar=two" ); ``` -------------------------------- ### DeferredList example: fetch data from two URLs Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Async.html Creates two loadJSONDoc Deferreds and combines them with a DeferredList. The callback receives a list of (success, result) tuples and alerts the data or error for each. The consumeErrors option is set to true. ```javascript // We need to fetch data from 2 different urls var d1 = loadJSONDoc(url1); var d2 = loadJSONDoc(url2); var l1 = new DeferredList([d1, d2], false, false, true); l1.addCallback(function (resultList) { MochiKit.Base.map(function (result) { if (result[0]) { alert("Data is here: " + result[1]); } else { alert("Got an error: " + result[1]); } }, resultList); }); ``` -------------------------------- ### Using afterFinish callback with slideUp Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Visual.html Shows how to define a custom callback for the afterFinish event in an effect's options. The example slides an element up and then down again after the first effect finishes. ```javascript // I slide it up and then down again slideUp('myelement', { afterFinish: function () { slideDown('myelement'); } }); ``` -------------------------------- ### Creating a table with MochiKit.DOM Source: https://mochi.github.io/mochikit/doc/html/MochiKit/DOM.html Shows how to build a table with header, footer, and body rows using MochiKit.DOM's tag functions and the map/partial helpers. The example creates a new table and swaps it into the document, replacing an existing element. ```javascript var rows = [ ["dataA1", "dataA2", "dataA3"], ["dataB1", "dataB2", "dataB3"] ]; row_display = function (row) { return TR(null, map(partial(TD, null), row)); } var newTable = TABLE({'class': 'prettytable'}, THEAD(null, row_display(["head1", "head2", "head3"])), TFOOT(null, row_display(["foot1", "foot2", "foot3"])), TBODY(null, map(row_display, rows))); // put that in your document.createElement and smoke it! swapDOM(oldTable, newTable); ``` -------------------------------- ### Signal for DOM events Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Signal.html Shows how to connect DOM events (e.g., 'onclick') to functions or methods, normalize the event object, stop default actions, and trigger fake DOM events. The event is normalized so no browser-specific code is needed. Use e.mouse().page to get cross-browser coordinates. The example also demonstrates triggering a fake event with signal(). ```javascript // DOM events are also signals. Connect freely! The functions will be // called with the custom event as a parameter. // calls myClicked.apply(getElement('myID'), [event]) connect('myID', 'onclick', myClicked); // calls wasClicked.apply(myObject, [event]) connect('myID', 'onclick', myObject, wasClicked); // calls myObject.wasClicked(event) connect('myID', 'onclick', myObject, 'wasClicked'); // the event is normalized, no more e = e || window.event! myObject.wasClicked = function(e) { var crossBrowserCoordinates = e.mouse().page; // e.mouse().page is an object like this { x: , y: } } // stops the default action for a click event connect('myID', 'onclick', function(e) { e.stop(); }); // triggers a fake DOM event for the above handler var fakeEvent = { /* add properties and functions needed here */ }; signal('myID', 'onclick', fakeEvent); ``` -------------------------------- ### range([start,] stop[, step]) Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Iter.html Returns an iterator containing an arithmetic progression of integers. The start defaults to 0, and the end point is omitted. ```APIDOC ## range([start,] stop[, step]) ### Description Returns an iterator containing an arithmetic progression of integers. `range(i, j)` returns iter([i, i + 1, i + 2, ..., j - 1]). `start` defaults to 0. When `step` is given, it specifies the increment (or decrement). The end point is omitted. ### Parameters - **start** (number) - Optional - The starting value of the sequence. Defaults to 0. - **stop** (number) - Required - The end value of the sequence (exclusive). - **step** (number) - Optional - The increment (or decrement) between each value. ### Returns An iterator containing the arithmetic progression of integers. ### Example ``` range(4) // returns iter([0, 1, 2, 3]) ``` ``` -------------------------------- ### sum(iterable, start=0) Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Iter.html Returns the sum of a sequence of numbers plus the value of parameter start (default 0). When the sequence is empty, returns start. ```APIDOC ## sum(iterable, start=0) ### Description Returns the sum of a sequence of numbers plus the value of parameter `start` (with a default of 0). When the sequence is empty, returns start. Equivalent to `reduce(operator.add, iterable, start)`. ### Parameters - **iterable** (iterable) - Required - The iterable of numbers to sum. - **start** (number) - Optional - The initial value to add to the sum. Defaults to 0. ### Returns The sum of the numbers plus the start value. ``` -------------------------------- ### Sequence(effects [, options]) Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Visual.html Launches a list of effects in sequence, one after the other. All effects must have sync set to true. ```APIDOC ## Sequence(effects [, options]) ### Description Launch a list of `effects` in sequence, one after the other. ### Parameters - **effects** (Array) - Required - An array of instantiated effect objects. Note that they _must_ all have `sync` set to `true`. - **options** (Object) - Optional - See DefaultOptions. Note that the default value for some options is different and that some of the transition and timing options don't make sense to override. - **transition** (String) - Optional - Default: `MochiKit.Visual.Transitions.linear` - **duration** (Number) - Optional - Default: Sum of the `duration` for all `effects`. - **from** (Number) - Optional - Default: Only `0.0` makes sense. - **to** (Number) - Optional - Default: Only `1.0` makes sense. ### Availability Available in MochiKit 1.4+ ``` -------------------------------- ### Safe JSON object example Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Async.html Example of a JSON object that is not vulnerable to the described exploit because JSON objects are not valid JavaScript syntax on their own without parentheses. ```json {"some_known_key": "this can't be leaked"} ``` -------------------------------- ### Vulnerable JSON array example Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Async.html Example of a JSON array that can be exploited for cross-site request forgery when used as the outer-most object, as it can be parsed as a script tag. ```json [{"some_known_key": "this can be leaked"}, "but not this"] ``` -------------------------------- ### queryString example: array-like values are expanded Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Base.html When a value is array-like, it is expanded as if it were a multiply defined HTML element. The example shows that an array value produces multiple name=value pairs. ```javascript assert( queryString({a: [1,2]}) === "a=1&a=2" ); ``` -------------------------------- ### NotFound error Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Base.html A singleton error raised when no suitable adapter is found. ```APIDOC ## NotFound ### Description A singleton error raised when no suitable adapter is found. ### Availability Available in MochiKit 1.3.1+ ``` -------------------------------- ### Synopsis: MochiKit.Text string helpers and formatting Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Text.html Shows usage of startsWith, endsWith, contains, padLeft, padRight, truncate, formatValue, format, and formatter. The assertions demonstrate expected results, including hex formatting, decimal precision, and percentage formatting. ```javascript assert( startsWith("ab", "abcd") ); assert( endsWith("cd", "abcd") ); assert( contains("bc", "abcd") ); assert( padLeft("abc", 5), " abc" ); assert( padRight("abc", 5, "*"), "abc**" ); assert( truncate("abcd", 2) == "ab" ); assert( formatValue("X", 31) == "1F" ); assert( format("{0}: {1:.3f}", "value", 1.2345) == "value: 1.234" ); assert( formatter("{:6.1%}")(0.125) == " 12.5%" ); ``` -------------------------------- ### parseQueryString example: use arrays for repeated names Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Base.html When the second argument is true, repeated names are stored as arrays. The example shows that 'foo' becomes an array with two values. ```javascript var args = parseQueryString("foo=one&foo=two", true); assert( args.foo[0] == "one" && args.foo[1] == "two" ); ``` -------------------------------- ### parseQueryString example: parse query string with default behavior Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Base.html Parses a URL query string into an object. The example shows that values are URL-decoded and the result is an object with properties for each name=value pair. ```javascript var args = parseQueryString("foo=value%20one&bar=two"); assert( args.foo == "value one" && args.bar == "two" ); ``` -------------------------------- ### Logger.prototype.debuggingBookmarklet() Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Logging.html Opens a debugging console using a bookmarklet. If MochiKit.LoggingPane is loaded, it uses that; otherwise, it falls back to alert messages. ```APIDOC ## Logger.prototype.debuggingBookmarklet() ### Description Opens a debugging console using a bookmarklet. If MochiKit.LoggingPane is loaded, it uses that; otherwise, it falls back to alert messages. ### Method N/A (JavaScript method) ### Endpoint N/A ### Parameters None. ### Request Example ```javascript logger.debuggingBookmarklet(); ``` ### Response No return value. ``` -------------------------------- ### module(parent, name, version, deps=[]) Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Base.html Creates a new module in a parent namespace with metadata and dependency checking. ```APIDOC ## module(parent, name, version, deps=[]) ### Description Creates a new `name` module in a `parent` namespace. This function will create a new empty module object with `NAME`, `VERSION`, `toString` and `__repr__` properties. It will also verify that all the strings in `deps` are defined in `parent`, or an error will be thrown. ### Availability Available in MochiKit 1.4+ ### Parameters - **parent** (Object) - Required - The parent module or namespace. Use `this` or `window` to create a global module. - **name** (String) - Required - The new module name. - **version** (String) - Required - The module version string, e.g. "1.5". - **deps** (Array) - Optional - The array of module dependencies, as strings. Defaults to []. ### Example ``` module(MochiKit, 'Iter', '1.5', ['Base']); ``` ``` -------------------------------- ### LoggingPane(inline=false, logger=MochiKit.Logging.logger) Source: https://mochi.github.io/mochikit/doc/html/MochiKit/LoggingPane.html Constructs a new LoggingPane instance that listens to a MochiKit.Logging logger and displays its output in an interactive DOM element, either inline or in a pop-up window. ```APIDOC ## LoggingPane(inline=false, logger=MochiKit.Logging.logger) ### Description Creates a new LoggingPane that listens to a MochiKit.Logging logger and displays its output in an interactive DOM element. If `inline` is true, the pane is a DIV at the bottom of the document; otherwise, it opens in a pop-up window. The `logger` parameter specifies which logger to listen to, defaulting to the global default logger. ### Parameters - **inline** (boolean) - Optional - If true, the pane is rendered as a DIV at the bottom of the document; otherwise, it opens in a pop-up window. Defaults to false. - **logger** (MochiKit.Logging.Logger) - Optional - The logger to listen to. Defaults to `MochiKit.Logging.logger`. ### Properties - **win** - Reference to the pop-up window, or `undefined` if inline. - **inline** - Boolean indicating whether the pane is inline. - **colorTable** - Object mapping log levels to colors. Can be mutated on `LoggingPane.prototype` to affect all instances. ### Example ``` MochiKit.LoggingPane.LoggingPane.prototype.colorTable = { DEBUG: "green", INFO: "black", WARNING: "blue", ERROR: "red", FATAL: "darkred" }; ``` ``` -------------------------------- ### withWindow(win, func) Source: https://mochi.github.io/mochikit/doc/html/MochiKit/DOM.html Calls a function with the window and document DOM Contexts set to the given window and its document, restoring the previous context after the function returns or throws. ```APIDOC ## withWindow(win, func) ### Description Calls func with the window DOM Context set to win and the document DOM Context set to win.document. When func() returns or throws an error, the DOM Context will be restored to its previous state. ### Method Function ### Parameters - **win** (window object) - Required - The window to set as the DOM Context. - **func** (function) - Required - The function to call. ### Returns The return value of func(). ### Availability Available in MochiKit 1.3.1+ ``` -------------------------------- ### findValue(lst, value, start=0, end=lst.length) Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Base.html Finds the index of value in the Array-like object lst using compare. The search starts at the index start, and ends at the index end - 1. If value is not found in lst, it will return -1. ```APIDOC ## findValue(lst, value, start=0, end=lst.length) ### Description Finds the index of `value` in the `Array`-like object `lst` using compare. The search starts at the index `start`, and ends at the index `end - 1`. If `value` is not found in `lst`, it will return `-1`. ### Parameters - **lst** (Array-like) - Required - The array-like object to search. - **value** (Any) - Required - The value to search for. - **start** (Number) - Optional - The index to start the search. Default is 0. - **end** (Number) - Optional - The index to end the search (exclusive). Default is `lst.length`. ### Returns - **Number** - The index of the first occurrence of `value`, or `-1` if not found. ### Example ``` assert( findValue([1, 2, 3, 2, 1], 2) == 1 ) assert( findValue([1, 2, 3, 2, 1], 2, 2) == 3 ) ``` ### Availability Available in MochiKit 1.3.1+ ``` -------------------------------- ### range([start,] stop[, step]) Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Iter.html Returns an iterator of numbers in a range. ```APIDOC ## range([start,] stop[, step]) ### Description Returns an iterator that yields numbers from `start` (default 0) up to but not including `stop`, with a step of `step` (default 1). ### Parameters - **start** (number) - Optional - The starting value (default 0). - **stop** (number) - Required - The stopping value (exclusive). - **step** (number) - Optional - The step size (default 1). ### Returns An iterator of numbers. ``` -------------------------------- ### count(n=0) Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Iter.html Returns an infinite iterator of consecutive integers starting from n. ```APIDOC ## count(n=0) ### Description Returns an infinite iterator that generates consecutive integers starting from `n` (default 0). ### Parameters - **n** (number) - Optional - The starting value (default 0). ### Returns An infinite iterator of consecutive integers. ``` -------------------------------- ### grow(element [, options]) Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Visual.html Grows an element's size using Scale, Move and Opacity effects in parallel. The element should have fixed width, height and top-left position. Before the effect starts, the element is shown and its size and position values are read. ```APIDOC ## grow(element [, options]) ### Description Grows an `element` size using Scale, Move and Opacity effects in parallel. The `element` should have fixed width, height and top-left position. Before the effect starts, the `element` will be shown with MochiKit.Style.showElement and the size and position values will be read. ### Parameters - **element** (string | DOM node) - Required - An element ID string or a DOM node (see MochiKit.DOM.getElement). - **options** (object) - Optional - The following options and default values control this effect. Note that the Opacity effect is turned off by default. See also the DefaultOptions. - **direction** (string) - Optional - Default: `"center"`. Controls the origin point of the effect. Allowed values: `"center"`, `"top-left"`, `"top-right"`, `"bottom-left"`, `"bottom-right"`. - **moveTransition** (function) - Optional - Default: `MochiKit.Visual.Transitions.sinoidal`. - **scaleTransition** (function) - Optional - Default: `MochiKit.Visual.Transitions.sinoidal`. - **opacityTransition** (function) - Optional - Default: `MochiKit.Visual.Transitions.full`. ### Availability Available in MochiKit 1.4+ ``` -------------------------------- ### Partial application with partial(compare, 1) Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Base.html Creates a partially applied function that compares a given object to a list of objects. The example shows that compareWithOne is created by partially applying compare with 1, then mapping it over [0,1,2,3] to produce [-1,0,1,1]. ```javascript compareWithOne = partial(compare, 1); results = map(compareWithOne, [0, 1, 2, 3]); assert( objEqual(results, [-1, 0, 1, 1]) ); ``` -------------------------------- ### islice(seq, [start,] stop[, step]) Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Iter.html Returns an iterator that yields selected elements from a sequence. ```APIDOC ## islice(seq, [start,] stop[, step]) ### Description Returns an iterator that yields elements from `seq` starting at `start` (default 0), up to but not including `stop`, with a step of `step` (default 1). ### Parameters - **seq** (iterable) - Required - The sequence to slice. - **start** (number) - Optional - The starting index (default 0). - **stop** (number) - Required - The stopping index (exclusive). - **step** (number) - Optional - The step size (default 1). ### Returns An iterator of the selected elements. ``` -------------------------------- ### Synopsis: Color usage examples Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Color.html Shows basic usage of MochiKit.Color: parsing RGB strings, creating colors from RGB and HSL values, parsing SVG color names, and converting to hex strings. Note that fromRGB and fromHSL take numbers between 0.0 and 1.0. ```javascript // RGB color expressions are supported assert( objEqual(Color.whiteColor(), Color.fromString("rgb(255,100%, 255)")) ); // So is instantiating directly from HSL or RGB values. // Note that fromRGB and fromHSL take numbers between 0.0 and 1.0! assert( objEqual(Color.fromRGB(1.0, 1.0, 1.0), Color.fromHSL(0.0, 0.0, 1.0) ); // Or even SVG color keyword names, as per CSS3! assert( Color.fromString("aquamarine"), "#7fffd4" ); // NSColor-like colors built in assert( Color.whiteColor().toHexString() == "#ffffff" ); ``` -------------------------------- ### doSimpleXMLHttpRequest(url[, queryArguments...]) Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Async.html Performs a simple GET XMLHttpRequest with optional query arguments. ```APIDOC ## doSimpleXMLHttpRequest(url[, queryArguments...]) ### Description Performs a simple GET XMLHttpRequest to the given URL, appending any query arguments to the URL. Returns a Deferred that resolves with the response. ### Method Function ### Parameters - **url** (string) - Required - The URL to request. - **queryArguments...** (object) - Optional - An object or objects containing query parameters to append to the URL. ### Returns A Deferred that resolves with the XMLHttpRequest object on success. ``` -------------------------------- ### split vs built-in split example Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Text.html Shows the difference between the built-in String.split and MochiKit.Text.split when a max split count is given. The built-in stops after the max splits, while MochiKit.Text.split returns all parts up to max splits plus the remainder. ```python >>> "lovely bunch of coconuts".split(" ", 2) ["lovely", "bunch"] >>> MochiKit.Text.split("lovely bunch of coconuts", " ", 2) ["lovely", "bunch", "of coconuts"] ``` -------------------------------- ### findIdentical(lst, value, start=0, end=lst.length) Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Base.html Finds the index of value in the Array-like object lst using the === operator. The search starts at the index start, and ends at the index end - 1. If value is not found in lst, it will return -1. Use this instead of findValue when you need to find an identical object or when performance is important for primitive arrays. ```APIDOC ## findIdentical(lst, value, start=0, end=lst.length) ### Description Finds the index of `value` in the `Array`-like object `lst` using the `===` operator. The search starts at the index `start`, and ends at the index `end - 1`. If `value` is not found in `lst`, it will return `-1`. You should use this function instead of findValue if `lst` may be comprised of objects for which no comparator is defined and all you care about is finding an identical object (e.g. the same instance), or if `lst` is comprised of just numbers or strings and performance is important. ### Parameters - **lst** (Array-like) - Required - The array-like object to search. - **value** (Any) - Required - The value to search for. - **start** (Number) - Optional - The index to start the search. Default is 0. - **end** (Number) - Optional - The index to end the search (exclusive). Default is `lst.length`. ### Returns - **Number** - The index of the first occurrence of `value`, or `-1` if not found. ### Example ``` assert( findIdentical([1, 2, 3, 2, 1], 2) == 1 ) assert( findIdentical([1, 2, 3, 2, 1], 2, 2) == 3 ) ``` ### Availability Available in MochiKit 1.3.1+ ``` -------------------------------- ### Parallel(effects [, options]) Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Visual.html Launches a list of effects in parallel. All effects must have sync set to true. ```APIDOC ## Parallel(effects [, options]) ### Description Launch a list of `effects` in parallel. ### Parameters - **effects** (Array) - Required - An array of instantiated effect objects. Note that they _must_ all have `sync` set to `true`. - **options** (Object) - Optional - See DefaultOptions. ### Availability Available in MochiKit 1.4+ ``` -------------------------------- ### Logging synopsis with log and logDebug Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Logging.html Shows basic usage of the log and logDebug functions. The log function can accept multiple arguments, allowing convenient passing of objects. ```javascript log("INFO messages are so boring"); logDebug("DEBUG messages are even worse"); log("good thing I can pass", objects, "conveniently"); ``` -------------------------------- ### getNodeAttribute(node, attr) Source: https://mochi.github.io/mochikit/doc/html/MochiKit/DOM.html Gets the value of an attribute without raising exceptions, handling IE quirks. ```APIDOC ## getNodeAttribute(node, attr) ### Description Get the value of the given attribute for a DOM element without ever raising an exception (will return `null` on exception). Note that it will do the right thing for IE, so don't do the `class` -> `className` hack yourself. ### Parameters - **node** (DOM element or string) - Required - A reference to the DOM element to update (if a string is given, getElement(node) will be used to locate the node) - **attr** (string) - Required - The name of the attribute ### Returns - The attribute's value, or `null` ### Availability Available in MochiKit 1.3.1+ ``` -------------------------------- ### counter(n=1) Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Base.html Returns a function that returns a number one greater than the previous returned value, starting at n. ```APIDOC ## counter(n=1) ### Description Returns a function that will return a number one greater than the previous returned value, starting at `n`. ### Parameters - **n** (Number) - Optional - The starting value. Defaults to 1. ### Example ``` nextId = counter() assert( nextId() == 1 ) assert( nextId() == 2 ) ``` ### Availability Available in MochiKit 1.3.1+ ``` -------------------------------- ### Create LoggingPane as pop-up or inline Source: https://mochi.github.io/mochikit/doc/html/MochiKit/LoggingPane.html Shows two ways to create a logging pane: as a pop-up window (default) or as a div at the bottom of the document. The inline parameter controls the display mode. ```javascript // open a pop-up window createLoggingPane() // use a div at the bottom of the document createLoggingPane(true); ``` -------------------------------- ### Deferred internal representation Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Async.html The internal representation of the Deferred callback sequence after adding callbacks as shown in the previous example. ```javascript [ [myCallback, null], [null, myErrback], [myBoth, myBoth], [myCallback, myErrback] ] ``` -------------------------------- ### counter: Generate incrementing numbers Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Base.html Creates a counter starting at 1 and verifies it returns 1 then 2 on successive calls. ```javascript nextId = counter() assert( nextId() == 1 ) assert( nextId() == 2 ) ``` -------------------------------- ### key() Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Signal.html Returns an object with key code and string representation for keyboard events. ```APIDOC ## key() ### Description Returns `{code, string}`. Use `'onkeydown'` and `'onkeyup'` handlers to detect control characters such as `'KEY_F1'`. Use the `'onkeypress'` handler to detect "printable" characters, such as `'é'`. When a user presses F1, in `'onkeydown'` and `'onkeyup'` this method returns `{code: 122, string: 'KEY_F1'}`. In `'onkeypress'`, it returns `{code: 0, string: ''}`. If a user presses Shift+2 on a US keyboard, this method returns `{code: 50, string: 'KEY_2'}` in `'onkeydown'` and `'onkeyup'`. In `'onkeypress'`, it returns `{code: 64, string: '@'}`. See `_specialKeys` in the source code for a comprehensive list of control characters. ### Availability Available in MochiKit 1.3.1+ ``` -------------------------------- ### camelize: Convert hyphenated string to camelCase Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Base.html Example of camelize converting 'border-left' to 'borderLeft'. Uses assert to verify the result. ```javascript assert( camelize("border-left") == "borderLeft" ); ``` -------------------------------- ### toHexString example Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Color.html Asserts that whiteColor().toHexString() returns '#FFFFFF'. Note that alpha is completely ignored for hexadecimal string representations. ```javascript assert( Color.whiteColor().toHexString() == "#FFFFFF" ); ``` -------------------------------- ### padRight(str, minLength, fillChar=" ") Source: https://mochi.github.io/mochikit/doc/html/MochiKit/Text.html Pads the string str on the right with fillChar until it reaches minLength. ```APIDOC ## padRight(str, minLength, fillChar=" ") ### Description Pads the string str on the right with fillChar until it reaches minLength. ### Method padRight ### Parameters - **str** (string) - Required - The string to pad. - **minLength** (number) - Required - The minimum length of the resulting string. - **fillChar** (string) - Optional - The character to pad with. Defaults to " ". ### Returns - **string** - The padded string. ### Example ``` assert( padRight("abc", 5, "*"), "abc**" ); ``` ```