diff --git a/dev/config.js b/dev/config.js index 8585034..592bc7a 100644 --- a/dev/config.js +++ b/dev/config.js @@ -22,7 +22,7 @@ module.exports = [ }, { "type": "input", - "app_key": "email", + "appKey": "email", "value": "", "label": "Email", "attributes": { @@ -34,13 +34,13 @@ module.exports = [ }, { "type": "toggle", - "app_key": "like_stuff", + "appKey": "cool_stuff", "label": "Enable Cool Stuff", "value": false }, { "type": "color", - "app_key": "background", + "appKey": "background", "value": "0xFF0000", "label": "Background Color" } @@ -56,7 +56,7 @@ module.exports = [ { "id": "flavor", "type": "select", - "app_key": "flavor", + "appKey": "flavor", "value": "grape", "label": "Favorite Flavor", "options": [ diff --git a/dev/custom-fn.js b/dev/custom-fn.js index a65dfb0..1af6daa 100644 --- a/dev/custom-fn.js +++ b/dev/custom-fn.js @@ -1,15 +1,15 @@ 'use strict'; module.exports = function() { - var Api = window.Clay = this; + var Clay = this; - var testHandler = function() { - console.debug('KEEGAN: this', this); - console.debug('KEEGAN: arguments', arguments); -// Api.getItemByAppKey('background').off(testHandler); - }; + Clay.getItemByAppKey('cool_stuff').on('change', function() { + if (this.get()) { + Clay.getItemByAppKey('background').enable(); + } else { + Clay.getItemByAppKey('background').disable(); + } + }); - Api.getItemByAppKey('background').on('change', testHandler); - - console.debug('custom fn worked'); + Clay.getSettings(); }; diff --git a/src/scripts/config-page.js b/src/scripts/config-page.js index 21a7541..4358734 100755 --- a/src/scripts/config-page.js +++ b/src/scripts/config-page.js @@ -1,28 +1,16 @@ 'use strict'; -/** - * A Clay config Item - * @typedef {object} Clay~Item - * @property {string} type - * @property {string} app_key - * @property {string} id - * @property {string} content - * @property {string|boolean} default - * @property {string} label - * @property {object} attributes - * @property {Array} options - * @property {Array} items - */ - -var itemTypes = require('./lib/items'); var $ = require('./vendor/minified/minified').$; var _ = require('./vendor/minified/minified')._; -var HTML = require('./vendor/minified/minified').HTML; - +var Api = require('./lib/api'); var config = _.extend([], window.clayConfig || []); + var settings = _.extend({}, window.claySettings || {}); var returnTo = window.returnTo || 'pebblejs://close#'; -var customFn = window.customFn; +var customFn = window.customFn || function() {}; + +var api = new Api(settings); +var $mainForm = $('#main-form'); function submit(event) { _.each(api.itemsByAppKey, function(appKey, item) { @@ -34,132 +22,8 @@ function submit(event) { return false; } -/** - * - * @param {string} key - * @param {string|boolean} defaultValue - * @return {string|boolean} - */ -function getSetting(key, defaultValue) { - return typeof settings[key] !== 'undefined' ? settings[key] : (defaultValue || ''); -} +api.addItem(config, $mainForm); -// function setSetting(key, value) { -// settings[key] = value; -// } +//$mainForm.on('submit', submit); -/** - * @param {Clay~Item|Array} item - * @param {$} $parent - */ -function processConfigItem(item, $parent) { - // @todo add validation on the Item - - if (Array.isArray(item)) { - item.forEach(function(item) { - processConfigItem(item, $parent); - }); - } else if (item.type === 'section') { - var $container = HTML('
var obj = {a: 2, b: 52};
+ * var keys = _.keys(obj); // keys contains ['a', 'b'] now
+ *
+ *
+ * @param object The object to gather keys from.
+ * @return A Minified list containing the property names.
+ *
+ * @see ##_.values() returns the values of an object as a list.
+ */
+ 'keys': funcArrayBind(keys),
+
+ /*$
+ * @id objvalues
+ * @group OBJECT
+ * @requires
+ * @configurable default
+ * @name _.values()
+ * @syntax _.values(obj)
+ * @module UTIL
+ * Creates a ##list#Minified list## containing all property values of the specified object. Only direct properies are
+ * included, not inherited ones. The order of the values in the list is undefined and runtime-specific.
+ *
+ * @example Using values():
+ * var obj = {a: 2, b: 52};
+ * var values = _.values(obj); // keys contains [2, 52] now
+ *
+ *
+ * @param object The object to gather values from.
+ * @return A Minified list containing the property names.
+ *
+ * @see ##_.keys() retrieves the property names of an object as a list.
+ */
+ 'values': funcArrayBind(function(obj, keys) {
+ var list = [];
+ if (keys)
+ each(keys, function(value) { list.push(obj[value]); });
+ else
+ eachObj(obj, function(key, value) { list.push(value); });
+ return list;
+ }),
+
+ /*$
+ * @id copyobj
+ * @group OBJECT
+ * @requires
+ * @configurable default
+ * @name _.copyObj()
+ * @syntax _.copyObj(from)
+ * @syntax _.copyObj(from, to)
+ * @module UTIL
+ * Copies every property of the first object into the second object. The properties are copied as shallow-copies.
+ *
+ * @example Copying properties:
+ * var target = {a:3, c: 3};
+ * _.copyObj({a: 1, b: 2}, target); // target is now {a: 1, b: 2, c: 3}
+ *
+ * @example Inline property merge:
+ * var target = _.copyObj({a: 1, b: 2}, {a:3, c: 3}); // target is now {a: 1, b: 2, c: 3}
+ *
+ * @example Duplicating an object:
+ * var target = _.copyObj({a: 1, b: 2}); // target is now {a: 1, b: 2}
+ *
+ * @param from the object to copy from
+ * @param to optional the object to copy to. If not given, a new object will be created.
+ * @return the object that has been copied to
+ *
+ * @see ##_.extend() is very similar to copyObj(), but with a slightly different syntax.
+ * @see ##_.merge() copies a list of objects into a new object.
+ */
+ 'copyObj': copyObj,
+
/*$
* @id extend
* @group OBJECT
@@ -2848,6 +2931,46 @@ define('minified', function() {
return result;
},
+ /*$
+ * @id filterobj
+ * @group OBJECT
+ * @requires
+ * @configurable default
+ * @name _.filterObj()
+ * @syntax _.filterObj(obj, filterFunc)
+ * @syntax _.filterObj(obj, filterFunc, ctx)
+ * @module UTIL
+ * Creates a new object that contains only those properties of the input object that have been approved by the filter function.
+ *
+ * If the callback function returns true, the property and its value are shallow-copied in the new object, otherwise it will be removed.
+ *
+ * @example Removing all values over 10 from an object:
+ *
+ * var list = _.filterObj({a: 4, b: 22, c: 7, d: 2, e: 19}, function(key, value) {
+ * return value <= 10;
+ * });
+ *
+ *
+ * @param obj the object to use
+ * @param callback The callback function(key, value) to invoke for each property.
+ *
- * define('makeGreen', function(require) {
- * var MINI = require('minified'), $ = MINI.$; // obtain own ref to Minified
- * return function(list) {
- * $(list).set({$color: '#0f0', $backgroundColor: '#050'});
- * });
- * });
- *
- * var makeGreen = require('makeGreen');
- * makeGreen('.notGreenEnough');
- *
- *
- * @param name the name of the module to request. In Minified's implementation, only 'minified' is supported.
- * @param factoryFunction is a function(require) will be called the first time the name is defined to obtain the module
- * reference. It received a reference to ##require() (which is required for AMD backward-compatibility) and
- * must return the value that is returned by ##require(). The function will only be called once, its result will
- * be cached.
- * define() function.
- */
-if (/^u/.test(typeof define)) { // no AMD support available ? define a minimal version
- (function(def){
- var require = this['require'] = function(name) { return def[name]; };
- this['define'] = function(name, f) { def[name] = def[name] || f(require); };
- })({});
-}
-/*$
- * @stop
- */
-
-define('minified', function() {
-
- ///#/snippet commonAmdStart
- ///#snippet webVars
- /*$
- * @id WEB
- * @doc no
- * @required
- * This id allows identifying whether the Web module is available.
- */
-
- /**
- * @const
- */
- var _window = window;
-
- /**
- * @const
- * @type {!string}
- */
- var MINIFIED_MAGIC_NODEID = 'Nia';
-
- /**
- * @const
- * @type {!string}
- */
- var MINIFIED_MAGIC_PREV = 'NiaP';
-
- var setter = {}, getter = {};
-
- var idSequence = 1; // used as node id to identify nodes, and as general id for other maps
-
-
- /*$
- * @id ready_vars
- * @dependency
- */
- /** @type {!Array.var p = _.promise();
- * setTimeout(function() {
- * p.fire(true);
- * }, 1000);
- *
- *
- * @example Request three files in parallel. When all three have been downloaded, concatenate them into a single string.
- *
- * var files = _('fileA.txt', 'fileA.txt', 'fileC.txt');
- * var content;
- * _.promise(files.map(function(file) {
- * return $.request('get', '/txts/' + file);
- * })).then(function(fileRslt1, fileRslt2, fileRslt3) {
- * content = _(fileRslt1, fileRslt2, fileRslt3).map( function(result) { return result[0]; }).join('');
- * }).error(function(status, response, xhr, url) {
- * alert('failed to load file '+url);
- * });
- *
- *
- * @param otherPromises one or more promises to assimilate (varargs). You can also pass lists of promises.
- * @return the new promise.
- */
- function promise() {
- var deferred = []; // this function calls the functions supplied by then()
-
- var assimilatedPromises = arguments;
- var assimilatedNum = assimilatedPromises.length;
- var numCompleted = 0; // number of completed, assimilated promises
- var rejectionHandlerNum = 0;
-
- var obj = new Promise();
-
- obj['errHandled'] = function() {
- rejectionHandlerNum++;
- if (obj['parent'])
- obj['parent']['errHandled']();
- };
-
- /*$
- * @id fire
- * @name promise.fire()
- * @syntax _.fire(newState)
- * @syntax _.fire(newState, values)
- * @module WEB+UTIL
- *
- * Changes the state of the promise into either fulfilled or rejected. This will also notify all ##then() handlers. If the promise
- * already has a state, the call will be ignored.
- *
- * fire() can be invoked as a function without context ('this'). Every promise has its own instance.
- *
- * @example A simple promise that is fulfilled after 1 second, using Minified's invocation syntax:
- * var p = _.promise();
- * setTimeout(function() {
- * p.fire(true, []);
- * }, 1000);
- *
- *
- * @example Call fire() without a context:
- * var p = _.promise(function(resolve, reject) {
- * setTimeout(resolve.fire, 1000);
- * });
- *
- *
- * @param newState true to set the Promise to fulfilled, false to set the state as rejected. If you pass null or
- * undefined, the promise's state does not change.
- * @param values optional an array of values to pass to ##then() handlers as arguments. You can also pass a non-list argument, which will then
- * be passed as only argument.
- * @return the promise
- */
- var fire = obj['fire'] = function(newState, newValues) {
- if (obj['state'] == null && newState != null) {
- obj['state'] = !!newState;
- obj['values'] = isList(newValues) ? newValues : [newValues];
- setTimeout(function() {
- each(deferred, function(f) {f();});
- }, 0);
- }
- return obj;
- };
-
- // use promise varargs
- each(assimilatedPromises, function assimilate(promise, index) {
- try {
- if (promise['then'])
- promise['then'](function(v) {
- var then;
- if ((isObject(v) || isFunction(v)) && isFunction(then = v['then']))
- assimilate(v, index);
- else {
- obj['values'][index] = array(arguments);
- if (++numCompleted == assimilatedNum)
- fire(true, assimilatedNum < 2 ? obj['values'][index] : obj['values']);
- }
- },
- function(e) {
- obj['values'][index] = array(arguments);
- fire(false, assimilatedNum < 2 ? obj['values'][index] : [obj['values'][index][0], obj['values'], index]);
- });
- else
- promise(function() {fire(true, array(arguments));}, function() {fire(false, array(arguments)); });
- }
- catch (e) {
- fire(false, [e, obj['values'], index]);
- }
- });
-
- /*$
- * @id stop
- * @name promise.stop()
- * @syntax promise.stop()
- * @module WEB+UTIL
- * Stops an ongoing operation, if supported. Currently the only promises supporting this are those returned by ##request(), ##animate(), ##wait() and
- * ##asyncEach().
- * stop() invocation will be propagated over promises returned by ##then() and promises assimilated by ##promise(). You only need to invoke stop
- * with the last promise, and all dependent promises will automatically stop as well.
- *
- * stop() can be invoked as a function without context ('this'). Every promise has its own instance.
- *
- * @return In some cases, the stop() can return a value. This is currently only done by ##animate() and ##wait(), which will return the actual duration.
- * ##asyncEach()'s promise will also return any value it got from the promise that it stopped.
- *
- * @example Animation chain that can be stopped.
- *
- * var div = $('#myMovingDiv').set({$left: '0px', $top: '0px'});
- * var prom = div.animate({$left: '200px', $top: '0px'}, 600, 0)
- * .then(function() {
- * return _.promise(div.animate({$left: '200px', $top: '200px'}, 800, 0),
- * div.animate({$backgroundColor: '#f00'}, 200));
- * }).then(function() {
- * return div.animate({$left: '100px', $top: '100px'}, 400);
- * });
- *
- * $('#stopButton').on('click', prom.stop);
- *
- */
- obj['stop'] = function() {
- each(assimilatedPromises, function(promise) {
- if (promise['stop'])
- promise['stop']();
- });
-
- return obj['stop0'] && call(obj['stop0']);
- };
-
- /*$
- * @id then
- * @name promise.then()
- * @syntax promise.then()
- * @syntax promise.then(onSuccess)
- * @syntax promise.then(onSuccess, onError)
- *
- * @module WEB
- * Registers two callbacks that will be invoked when the ##promise#Promise##'s asynchronous operation finished
- * successfully (onSuccess) or an error occurred (onError). The callbacks will be called after
- * then() returned, from the browser's event loop.
- * You can chain then() invocations, as then() returns another Promise object that you can attach to.
- *
- * The full distribution of Minified implements the Promises/A+ specification, allowing interoperability with other Promises frameworks.
- *
- * Note: If you use the Web module, you will get a simplified Promises implementation that cuts some corners. The most notable
- * difference is that when a then() handler throws an exception, this will not be caught and the promise returned by
- * then will not be automatically rejected.
- *
- * @example Simple handler for an HTTP request. Handles only success and ignores errors.
- *
- * $.request('get', '/weather.html')
- * .then(function(txt) {
- * alert('Got response!');
- * });
- *
- *
- * @example Including an error handler.
- *
- * $.request('get', '/weather.html')
- * .then(function(txt) {
- * alert('Got response!');
- * }, function(err) {
- * alert('Error!');
- * }));
- *
- *
- * @example Chained handler.
- *
- * $.request('get', '/weather.do')
- * .then(function(txt) {
- * showWeather(txt);
- * }
- * .then(function() {
- * return $.request('get', '/traffic.do');
- * }
- * .then(function(txt) {
- * showTraffic(txt);
- * }
- * .then(function() {
- * alert('All result displayed');
- * }, function() {
- * alert('An error occurred');
- * });
- *
- *
- * @param onSuccess optional a callback function to be called when the operation has been completed successfully. The exact arguments it receives depend on the operation.
- * If the function returns a ##promise#Promise##, that Promise will be evaluated to determine the state of the promise returned by then(). If it returns any other value, the
- * returned Promise will also succeed. If the function throws an error, the returned Promise will be in error state.
- * Pass null or undefined if you do not need the success handler.
- * @param onError optional a callback function to be called when the operation failed. The exact arguments it receives depend on the operation. If the function returns a ##promise#Promise##, that promise will
- * be evaluated to determine the state of the Promise returned by then(). If it returns anything else, the returned Promise will
- * have success status. If the function throws an error, the returned Promise will be in the error state.
- * You can pass null or undefined if you do not need the error handler.
- * @return a new ##promise#Promise## object. If you specified a callback for success or error, the new Promises's state will be determined by that callback if it is called.
- * If no callback has been provided and the original Promise changes to that state, the new Promise will change to that state as well.
- */
- var then = obj['then'] = function (onFulfilled, onRejected) {
- var promise2 = promise();
- var callCallbacks = function() {
- try {
- var f = (obj['state'] ? onFulfilled : onRejected);
- if (isFunction(f)) {
- (function resolve(x) {
- try {
- var then, cbCalled = 0;
- if ((isObject(x) || isFunction(x)) && isFunction(then = x['then'])) {
- if (x === promise2)
- throw new TypeError();
- then.call(x, function(x) { if (!cbCalled++) resolve(x); }, function(value) { if (!cbCalled++) promise2['fire'](false, [value]);});
- promise2['stop0'] = x['stop'];
- }
- else
- promise2['fire'](true, [x]);
- }
- catch(e) {
- if (!(cbCalled++)) {
- promise2['fire'](false, [e]);
- if (!rejectionHandlerNum)
- throw e;
- }
- }
- })(call(f, undef, obj['values']));
- }
- else
- promise2['fire'](obj['state'], obj['values']);
- }
- catch (e) {
- promise2['fire'](false, [e]);
- if (!rejectionHandlerNum)
- throw e;
- }
- };
- if (isFunction(onRejected))
- obj['errHandled']();
- promise2['stop0'] = obj['stop'];
- promise2['parent'] = obj;
- if (obj['state'] != null)
- setTimeout(callCallbacks, 0);
- else
- deferred.push(callCallbacks);
- return promise2;
- };
-
- /*$
- * @id always
- * @group REQUEST
- * @name promise.always()
- * @syntax promise.always(callback)
- * @configurable default
- * @module WEB+UTIL
- * Registers a callback that will always be called when the ##promise#Promise##'s operation ended, no matter whether the operation succeeded or not.
- * This is a convenience function that will call ##then() with the same function for both arguments. It shares all of its semantics.
- *
- * @example Simple handler for a HTTP request.
- *
- * $.request('get', '/weather.html')
- * .always(function() {
- * alert('Got response or error!');
- * });
- *
- *
- * @param callback a function to be called when the operation has been finished, no matter what its result was. The exact arguments depend on the operation and may
- * vary depending on whether it succeeded or not. If the function returns a ##promise#Promise##, that Promise will
- * be evaluated to determine the state of the returned Promise. If provided and it returns regularly, the returned promise will
- * have success status. If it throws an error, the returned Promise will be in the error state.
- * @return a new ##promise#Promise## object. Its state is determined by the callback.
- */
- obj['always'] = function(func) { return then(func, func); };
-
- /*$
- * @id error
- * @group REQUEST
- * @name promise.error()
- * @syntax promise.error(callback)
- * @configurable default
- * @module WEB, UTIL
- * Registers a callback that will be called when the operation failed.
- * This is a convenience function that will invoke ##then() with only the second argument set. It shares all of its semantics.
- *
- * @example Simple handler for a HTTP request.
- *
- * $.request('get', '/weather.html')
- * .error(function() {
- * alert('Got error!');
- * });
- *
- *
- * @param callback a function to be called when the operation has failed. The exact arguments depend on the operation. If the function returns a ##promise#Promise##, that Promise will
- * be evaluated to determine the state of the returned Promise. If it returns regularly, the returned Promise will
- * have success status. If it throws an error, the returned Promise will be in error state.
- * @return a new ##promise#Promise## object. Its state is determined by the callback.
- */
- obj['error'] = function(func) { return then(0, func); };
-
- return obj;
- }
-
- ///#/snippet extrasFunctions
- ///#snippet extrasDocs
- /*$
- * @id length
- * @group SELECTORS
- * @requires dollar
- * @name list.length
- * @syntax length
- * @module WEB, UTIL
- *
- * Contains the number of elements in the ##list#Minified list##.
- *
- * @example With Web module:
- *
- * var list = $('input');
- * var myValues = {};
- * for (var i = 0; i < list.length; i++)
- * myValues[list[i].name] = list[i].value;
- *
- *
- * @example With Util module:
- * - * var list = _(1, 2, 3); - * var sum = 0; - * for (var i = 0; i < list.length; i++) - * sum += list[i]; - *- */ - /*$ - * @stop - */ - ///#/snippet extrasDocs - - ///#snippet utilM - - /* - * syntax: M(list, assimilateSublists) - * M(null, singleElement) - * - * - */ - /** @constructor */ - function M(list, assimilateSublists) { - var self = this, idx = 0; - if (list) - for (var i = 0, len = list.length; i < len; i++) { - var item = list[i]; - if (assimilateSublists && isList(item)) - for (var j = 0, len2 = item.length; j < len2; j++) - self[idx++] = item[j]; - else - self[idx++] = item; - } - else - self[idx++] = assimilateSublists; - - self['length'] = idx; - self['_'] = true; - } - - function _() { - return new M(arguments, true); - } - - ///#/snippet utilM - - //// LIST FUNCTIONS //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - copyObj({ - ///#snippet utilListFuncs - /*$ - * @id each - * @group LIST - * @requires - * @configurable default - * @name .each() - * @altname _.each() - * @syntax list.each(callback) - * @syntax list.each(callback, ctx) - * @syntax _.each(list, callback) - * @syntax _.each(list, callback, ctx) - * @module UTIL, WEB - * Invokes the given function once for each item in the list. The function will be called with the item as first parameter and - * the zero-based index as second. Unlike JavaScript's built-in forEach() it will be invoked for each item in the list, - * even if it is undefined. - * - * @example Creates the sum of all list entries. - *
- * var sum = 0;
- * _(17, 4, 22).each(function(item, index) {
- * sum += item;
- * });
- *
- *
- * @example The previous example with a native array:
- *
- * var sum = 0;
- * _.each([17, 4, 22], function(item, index) {
- * sum += item;
- * });
- *
- *
- * @example This goes through all h2 elements of the class 'section' on a web page and changes their content:
- *
- * $('h2.section').each(function(item, index) {
- * item.innerHTML = 'Section ' + index + ': ' + item.innerHTML;
- * });
- *
- *
- * @param list a list to iterate. Can be an array, a ##list#Minified list## or any other array-like structure with
- * length property.
- * @param callback The callback function(item, index) to invoke for each list element.
- * ==) will be used.
- *
- * @example Removing all instances of the number 10 from a list:
- * - * var list = _([4, 10, 22, 7, 2, 19, 10]).filter(10); - *- * - * @example Removing all numbers over 10 from a list: - *
- * var list = _([4, 22, 7, 2, 19]).filter(function(item, index) {
- * return item <= 10;
- * });
- *
- *
- * @example The previous example with a native array is input. Note that the result is always a ##list#Minified list##:
- *
- * var list = _.filter([4, 22, 7, 2, 19], function(item, index) {
- * return item <= 10;
- * });
- *
- *
- * @example Creates a list of all unchecked checkboxes on a web page:
- *
- * var list = $('input').filter(function(item, index) {
- * return item.getAttribute('type') == 'checkbox' && item.checked;
- * });
- *
- *
- * @param list a list to filter. A list to use as input. Can be an array, a ##list#Minified list## or any other array-like structure with
- * length property.
- * @param filterFunc The filter callback function(item, index) that decides which elements to include:
- * ==. Must not
- * be a function. Requires Util module.
- * @return the new, filtered ##list#list##
- *
- * @see ##only() offers selector-based filtering.
- */
- 'filter': listBindArray(filter),
-
- /*$
- * @id map
- * @group LIST
- * @requires
- * @configurable default
- * @name .map()
- * @altname _.map()
- * @syntax list.map(mapFunc)
- * @syntax list.map(mapFunc, ctx)
- * @syntax _.map(list, mapFunc)
- * @syntax _.map(list, mapFunc, ctx)
- * @module UTIL
- * Creates a new ##list#Minified list## from the current list using the given callback function.
- * The callback is invoked once for each element of the current list. The callback results will be added to the result list.
- *
- * map() is a simpler version of ##collect(). Unlike collect(), it always creates lists of the same size as the input list, but
- * it is easier to use if the resulting list should contain nulls or nested list.
- *
- * @example Goes through a list of numbers and creates a new list with each value increased by 1:
- *
- * var inced = _(3, 7, 11, 5, 19, 3).map(function(number, index) {
- * return number + 1;
- * });
- *
- *
- * @example The previous example with a native array is input. Note that the result is always a ##list#Minified list##:
- *
- * var inced = _.map([3, 7, 11, 5, 19, 3], function(number, index) {
- * return number + 1;
- * });
- *
- *
- * @param list a list to transform. Can be an array, a ##list#Minified list## or any other array-like structure with
- * length property.
- * @param mapFunc The callback function(item, index) to invoke for each item:
- *
- * var i = _(1, 2, -4, 5, 2, -1).find(function(value, index) { if (value < 0) return index; }); // returns 2
- *
-
- * @example Finds the index of the first 5 in the array:
- * - * var i = _.find([3, 6, 7, 6, 5, 4, 5], 5); // returns 4 (index of first 5) - *- * - * @example Determines the position of the element with the id '#wanted' among all li elements: - *
- * var elementIndex = $('li').find($$('#wanted'));
- *
- *
- * @example Goes through the elements to find the first div that has the class 'myClass', and returns this element:
- *
- * var myClassElement = $('div').find(function(e) { if ($(e).is('.myClass')) return e; });
- *
- *
- * @param list A list to use as input. Can be an array, a ##list#Minified list## or any other array-like structure with
- * length property.
- * @param findFunc The callback function(item, index) that will be invoked for every list item until it returns a non-null value:
- * - * <div id="comments">Here is some text.<br/></div> - *- * The next line appends a text node to the div: - *
- * $('#comments').add('Some additional text.');
- *
- * This results in:
- * - * <div id="comments">Here is some text.<br/>Some additional text.</div> - *- * - * @example Using the following HTML: - *
- * <ul id="myList"> - * <li>First list entry</li> - * <li>Second list entry</li> - * </ul> - *- * The following Javascript adds an element to the list: - *
- * $('#myList').add(EE('li', 'My extra point');
- *
- * This results in
- * - * <ul id="myList"> - * <li>First list entry</li> - * <li>Second list entry</li> - * <li>My extra point</li> - * </ul> - *- * - * @example Use a list to add several elements at once: - *
- * $('#comments').add([
- * EE('br'),
- * 'Some text',
- * EE('span', {'className': 'highlight'}, 'Some highlighted text')
- * ]);
- *
- *
- * @example If you need to customize the content, you can write a factory function:
- *
- * $('.chapter').add(function(parent, index) { return EE('h2', 'Chapter number ' + index); });
- *
- *
- * @param text a string or number to add as text node
- * @param node a DOM node to add to the list. If the list has more than one element, the given node will be added to the first element.
- * For all additional elements, the node will be cloned using ##clone().
- * @param list a list containing text and/or nodes. May also contain nested lists with nodes or text..
- * @param factoryFunction a function(listItem, listIndex) that will be invoked for each list element to create the nodes:
- *
- * $('div').on('click', function() {
- * this.style.backgroundColor = 'red'; // 'this' contains the element that caused the event
- * });
- *
- *
- * @example Registers a handler to call a method setStatus('running') using an inline function:
- *
- * $('#myButton').on('click', function() {
- * setStatus('running');
- * });
- *
- * The previous example can bere written like this, using on()'s args parameter:
- *
- * $('#myButton').on('click', setStatus, ['running']);
- *
- *
- * @example Adds two handlers on an input field. The event names are prefixed with '|' and thus keep their original behavior:
- *
- * $('#myInput').on('|keypress |keydown', function() {
- * // do something
- * });
- *
- *
- * @example Adds a click handler that will abort the operation by returning false, unless the user confirms it:
- *
- * $('#myLink').on('?click', function() {
- * return window.confirm('Really leave?');
- * });
- *
- *
- * @example Adds a button and registers a click handler for it using a sub-selector.
- *
- * $('#myForm').add(HTML("<li><button>click me</button></li>").on('button', 'click', myClickHandler));
- *
- *
- * @example Adds listeners for all clicks on a table's rows using the bubble selector 'tr'.
- *
- * $('#table').on('change', 'tr', function(event, index, selectedIndex) {
- * alert("Click on table row number: " + selectedIndex);
- * }, 'tr');
- *
- * Please note that bubble selectors will even listen to events for
- * table rows that have been added after you registered for the events.
- *
- * @param selector optional a selector string for ##dollar#$()## to register the event only on those children of the list elements that
- * match the selector.
- * Supports all valid parameters for $() except functions.
- * @param names the space-separated names of the events to register for, e.g. 'click'. Case-sensitive. The 'on' prefix in front of
- * the name must not used. You can register the handler for more than one event by specifying several
- * space-separated event names. If the name is prefixed
- * with '|' (pipe), the event will be passed through and the event's default actions will be executed by the browser.
- * If the name is prefixed with '?', the event will only be passed through if the handler returns true.
- * @param eventHandler the callback function(event, index) to invoke when the event has been triggered:
- *
- * $('#myButton').trigger('click');
- *
- *
- * @param name a single event name to trigger
- * @param eventObj optional an object to pass to the event handler, provided the handler does not have custom arguments.
- * Anything you pass here will be directly given to event handlers as event object, so you need to know what
- * they expect.
- * @return the list
- * @see ##on() registers events that can be triggered.
- */
- 'trigger': function (eventName, eventObj) {
- return this['each'](function(element, index) {
- var bubbleOn = true, el = element;
- while(el && bubbleOn) {
- eachObj(el['M'], function(id, f) {
- bubbleOn = bubbleOn && f(eventName, eventObj, element);
- });
- el = el['parentNode'];
- }
- });
- }
-
- /*$
- * @stop
- */
- // @cond !trigger dummyTrigger:0
- ,
- ///#/snippet webListFuncs
- ///#snippet extrasListFuncs
-
- /*$
- * @stop
- */
- dummyHt:0
- ///#/snippet extrasListFuncs
- }, M.prototype);
-
- //// DOLLAR FUNCTIONS ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- copyObj({
- ///#snippet webDollarFuncs
- /*$
- * @id request
- * @group REQUEST
- * @requires
- * @configurable default
- * @name $.request()
- * @syntax $.request(method, url)
- * @syntax $.request(method, url, data)
- * @syntax $.request(method, url, data, settings)
- * @module WEB
- * Initiates a HTTP request to the given URL, using XMLHttpRequest. It returns a ##promiseClass#Promise## object that allows you to obtain the result.
- *
- * @example Invokes a REST web service and parses the resulting document using JSON:
- *
- * $.request('get', 'http://service.example.com/weather', {zipcode: 90210})
- * .then(function(txt) {
- * var json = $.parseJSON(txt);
- * $('#weatherResult').fill('Today's forecast is is: ' + json.today.forecast);
- * })
- * .error(function(status, statusText, responseText) {
- * $('#weatherResult').fill('The weather service was not available.');
- * });
- *
- *
- * @example Sending a JSON object to a REST web service:
- *
- * var myRequest = { // create a request object that can be serialized via JSON
- * request: 'register',
- * entries: [
- * {name: 'Joe',
- * job: 'Plumber'
- * }
- * ]};
- *
- * function failureHandler() {
- * $('#registrationResult').fill('Registration failed');
- * }
- *
- * $.request('post', 'http://service.example.com/directory', $.toJSON(myRequest))
- * .then(function(txt) {
- * if (txt == 'OK')
- * $('#registrationResult').fill('Registration succeeded');
- * else
- * failureHandler();
- * })
- * .error(failureHandler);
- *
- *
- * @example Using HTTP authentication and a custom XMLHttpRequest property.
- * var handler = $.request('get', 'http://service.example.com/userinfo', null, {xhr: {withCredentials: true}, user: 'me', pass: 'secret'});
- *
- *
- * @param method the HTTP method, e.g. 'get', 'post' or 'head' (rule of thumb: use 'post' for requests that change data
- * on the server, and 'get' to request data). Not case sensitive.
- * @param url the server URL to request. May be a relative URL (relative to the document) or an absolute URL. Note that unless you do something
- * fancy on the server (keyword to google: Access-Control-Allow-Origin), you can only call URLs on the server your script originates from.
- * @param data optional data to send in the request, either as POST body or as URL parameters. It can be either a plain object as map of
- * parameters (for all HTTP methods), a string (for all HTTP methods), a DOM document ('post' only) or a FormData object ('post' only).
- * If the method is 'post', it will be sent as body, otherwise parameters are appended to the URL. In order to send several parameters with the
- * same name, use an array of values in the map. Use null as value for a parameter without value.
- * @param settings optional a map of additional parameters. Supports the following properties (all optional):
- * {withCredentials: true}.function(text, xhr):
- * function(statusCode, statusText, text):
- *
- * $.ready(function() {
- * $('#someElement').fill('ready() called');
- * });
- *
- *
- * @param handler the function() to be called when the HTML is ready.
- * @see ##dollar#$()## calls ready() when invoked with a function, offering a more convenient syntax.
- */
- 'ready': ready,
-
- /*$
- * @stop
- */
- dummyOff:null
- ,
- ///#/snippet webDollarFuncs
- ///#snippet extrasDollarFuncs
-
- /*$
- * @id wait
- * @group EVENTS
- * @configurable default
- * @requires promise
- * @name $.wait()
- * @syntax $.wait()
- * @syntax $.wait(durationMs)
- * @syntax $.wait(durationMs, args)
- * @module WEB+UTIL
- *
- * Creates a new ##promise#Promise## that will be fulfilled as soon as the specified number of milliseconds have passed. This is mainly useful for animation,
- * because it allows you to chain delays into your animation chain.
- *
- * The operation can be interrupted by calling the promise's ##stop() function.
- *
- * @example Chained animation using Promise callbacks. The element is first moved to the position 200/0, then to 200/200, waits for 50ms
- * and finally moves to 100/100.
- *
- * var div = $('#myMovingDiv').set({$left: '0px', $top: '0px'});
- * div.animate({$left: '200px', $top: '0px'}, 600, 0)
- * .then(function() {
- * div.animate({$left: '200px', $top: '200px'}, 800, 0);
- * }).then(function() {
- * return _.wait(50);
- * }).then(function() {
- * div.animate({$left: '100px', $top: '100px'}, 400);
- * });
- * });
- *
- *
- *
- * @param durationMs optional the number of milliseconds to wait. If omitted, the promise will be fulfilled as soon as the browser can run it
- * from the event loop.
- * @param args optional an array or list of arguments to pass to the promise handler
- * @return a ##promise#Promise## object that will be fulfilled when the time is over, or fail when the promise's ##stop() has been called.
- * The promise argument of a fulfilled promise is the args parameter as given to wait(). The returned promise supports ##stop()
- * to interrupt the promise.
- */
- 'wait': function(durationMs, args) {
- var p = promise();
- var id = setTimeout(function() {
- p['fire'](true, args);
- }, durationMs);
- p['stop0'] = function() { p['fire'](false); clearTimeout(id); };
- return p;
- }
-
- /*$
- * @stop
- */
- // @cond !wait dummyWait:0
-
- ///#/snippet extrasDollarFuncs
- }, $);
-
- //// UNDERSCORE FUNCTIONS ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
-
- copyObj({
- ///#snippet utilUnderscoreFuncs
- // @condblock filter
- 'filter': funcArrayBind(filter),
- // @condend
- // @condblock map
- 'map': funcArrayBind(map),
- // @condend
- // @condblock each
- 'each': each,
- // @condend
- // @condblock each
- 'toObject': toObject,
- // @condend
- // @condblock find
- 'find': find,
- // @condend
-
- /*$
- * @id extend
- * @group OBJECT
- * @requires
- * @configurable default
- * @name _.extend()
- * @syntax _.extend(target, src...)
- * @module UTIL
- * Copies every property of the source objects into the first object. The source objects are specified using variable arguments.
- * There can be more than one.
- * The properties are copied as shallow-copies.
- *
- * Please note: Unlike jQuery, extend does not directly add a function to extend Minified, although
- * you can use it to for this. To add a function to ##list#Minified lists##, add a property to
- * ##M#MINI.M##. If you want to extend $ or _, just assign the new function(s) as property.
- *
- * @example Copying properties:
- * var target = {a:3, c: 3};
- * _.extend(target, {a: 1, b: 2}); // target is now {a: 1, b: 2, c: 3}
- *
- * @example Using several source values:
- * var extend = _.extend({a: 1, b: 2}, {a:3, c: 3}, {d: 5}); // target is now {a: 1, b: 2, c: 3, d: 5}
- *
- * @param target the object to copy to
- * @param src the object(s) to copy from. Variable argument, there can be any number of sources. Nulls and undefined
- * parameters will be ignored.
- * @return the target
- *
- * @see ##_.copyObj() is very similar to extend(), but with a slightly different and more straightforward syntax.
- * @see ##_.merge() copies a list of objects into a new object.
- */
- 'extend': function(target) {
- return merge(sub(arguments, 1), target);
- },
-
- /*$
- * @id template
- * @group FORMAT
- * @requires date_constants
- * @configurable default
- * @name _.template()
- * @syntax _.template(template)
- * @syntax _.template(template, escapeFunction)
- * @module UTIL
- * Parses a Handlebars-like template to create a reusable template function.
- *
- * The syntax of the template uses a syntax that superficially looks like
- * Handlebars. Unlike Handlebars, it is based on raw JavaScript expressions and thus gives you
- * complete freedom, but also offers you shortcuts for formatting, iteration and conditionals.
- *
- * Every template can receive exactly one object as input. If you need more than one value as input, put all required values
- * into an object.
- *
- * Use double curly braces to embed a JavaScript expression and insert its result:
- * {{a}} plus {{b}} is {{a+b}}
- *
- * To use such a template, create it with template() and then execute the resulting function:
- * var myTemplate = _.template('{{a}} plus {{b}} is {{a+b}}');
- * var result = myTemplate({a: 5, b: 7});
- * If you pass an object as input, its properties will be mapped using JavaScript's with
- * statement and are available as variables throughout the template.
- *
- * If you have only a simple value to render, you can pass it directly and access it through the pre-defined
- * variable obj:
- * var myTemplate = _.template('The result is {{obj}}.');
- * var result = myTemplate(17);
- * Alternatively, you could also access the input as this, but be aware that JavaScript wraps simples types
- * such as Number and Boolean. this is the default, so you can omit it to get the same result:
- * var myTemplate = _.template('The result is {{ }}.');
- * var result = myTemplate(17);
- *
- * Minified templates can use ##_.formatValue() formats directly. Just separate them from the expression by
- * a double-colon:
- * The price is {{obj::#.00}}.
- *
- * Conditions can be expressed using if and else:
- * Hello {{if visits==0}}New{{else if visits<10}}Returning{{else}}Regular{{/if}} Customer.
- * You can use any JavaScript expression as condition.
- *
- * Use each to iterate through a list:
- * var myTemplate = _.template(
- * '{{each names}}{{this.firstName}} {{this.lastName}}{{/each}}');
- * var result = myTemplate({names: [{firstName: 'Joe', lastName: 'Jones'},
- * {firstName: 'Marc', lastName: 'Meyer'}]});
- * each will iterate through the members of the given object. It
- * calls its body for each item and put a reference to the item into this.
- * Optionally, you can specify up to two variables to store the value in and
- * the zero-based index of the current item:
- * var myTemplate = _.template(
- * '{{each value, index: names}}{{index}}. {{value.firstName}} {{value.lastName}}{{/each}}');
- *
- *
- * If you do not pass an expression to each, it will take the list from this:
- * var myTemplate = _.template('{{each value:}}{{value}};{{/each}}');
- * var result = myTemplate([1, 2, 3]);
- *
- * Beside lists, you can also iterate through the properties of an object. The property name will be stored
- * in the first given parameter and the value in this and the second parameter:
- * var myTemplate = _.template('{{each key, value: nicknames}}{{key}}: {{value}}{{/each}}');
- * var result = myTemplate({nicknames: {Matt: 'Matthew', John: 'Jonathan'} });
- *
- * Shorter version of the previous example that uses this for the value:
- * var myTemplate = _.template('{{each key: nicknames}}{{key}}: {{this}}{{/each}}');
- *
- * If you do not need the key, you can omit the variable specification:
- * var myTemplate = _.template('{{each nicknames}}{{this}}{{/each}}');
- *
- * You can define your own variables, using the regular JavaScript syntax, with 'var':
- * var myTemplate = _.template('{{var s=very.long.name, sum=a+b;}}{{s.desc}}, {{sum}}');
- *
- * In some situations, it may be inevitable to embed raw JavaScript in the template.
- * To embed JavaScript code, prefix the code with a '#':
- * var myTemplate = _.template(
- * '{{each}}{{#var sum = 0; for (var i = 0; i < 3; i++) sum += this.numbers[i]; }}{{sum}}{{/each}}');
- * var result = myTemplate([['Foreword', 'Intro'], ['Something', 'Something else']]);
- *
- *
- * By default, all output will be escaped. You can prevent this by using triple-curly-braces:
- * Here's the original: {{{rawText}}}.
- *
- * The template's JavaScript code is executed in a sandbox without access to global variables. Minified defines the
- * following variables for you:
- * | Name | Desciption |
|---|---|
| this | The template object outside of each. Inside eachs, the current value. |
| obj | The parameter given to the template function. |
| _ | A reference to Minified Util. |
| esc | The escape function given when the template has been defined. If no function has been given, - * a default function that returns the input unmodified. |
A function(text,...) that appends one or more strings to the template result. | |
| each | A function(listOrObject, eachCallback) that can iterate over lists or object properties.
- * The eachCallback is a function(key, value) for objects or function(value, index)
- * for arrays that will be invoked for each item.
- * |
function(inputString) that will be used
- * to escape all output:
- * _()- * - * @example Creating a list with three items: - *
_(1, 2, 3)- * - * @example Creating the same list, but by passing an array. One array level will be flattened: - *
_([1, 2, 3])- * - * @example Creating a list containing the arrays [1, 2] and [3, 4]. - *
_([[1, 2], [3, 4]])- * - * @example Merging two lists: - *
var a = _("a", "b", "c");
- * var b = _("x", "y", "z");
- * var merged = _(a, b); // contains _("a", "b", "c", "x", "y", "z")
- *
- *
- * @example Adding two elements to a list:
- * var a = _(1, 2, 3); - * var a4 = _(a, 4); // contains _(1, 2, 3, 4) - *- * - * @example Mixing different list types and single elements: - *
_(1, [], [2, 3], _(), _(4, 5)); // same content as _(1, 2, 3, 4, 5)- * - * @param item an item to add to the new list. If it is a list (as defined by ##_.isList()), its content will be to the new - * ##Minified list#list## (but NOT recursively). - */ - '_': _, - /*$ - * @stop - */ - ///#/snippet utilExports - ///#snippet webExports - - /*$ - * @id dollar - * @group SELECTORS - * @requires - * @dependency yes - * @name $() - * @syntax $() - * @syntax $(selector) - * @syntax $(selector, context) - * @syntax $(selector, context, childOnly) - * @syntax $(list) - * @syntax $(list, context) - * @syntax $(list, context, childOnly) - * @syntax $(object) - * @syntax $(object, context) - * @syntax $(object, context, childOnly) - * @syntax $(domreadyFunction) - * @module WEB - * Creates a new ##list#Minified list##, or register a DOMReady-handler. - * The most common usage is with a CSS-like selector. $() will then create a list containing all elements of the current HTML - * document that fulfill the filter conditions. Alternatively you can also specify a list of objects or a single object. - * Nested lists will automatically be flattened, and nulls will automatically be removed from the resulting list. - * If you call $() without any arguments, it will return an empty list. - * - * Additionally, you can specify a second argument to provide a context. Contexts only make sense if you selected - * HTML nodes with the first parameter. Then the context limits the resulting list to include only those nodes - * that are descendants of the context nodes. The context can be either a selector, a list or a single HTML node, and will be - * processed like the first argument. A third arguments allows you to limit the list to - * only those elements that are direct children of the context nodes (so a child of a child would be filtered out). - * - * The lists created by $() are the same type as the ##list#Minified lists## created by Util's #underscore#_() constructor and other - * Util methods. All Util methods work on lists created by $(). If you want to add your own methods to those lists, - * use ##M#MINI.M##. - * - * As a special shortcut, if you pass a function to $(), it will be registered using #ready#$.ready() to be executed - * when the DOM model is complete. - * - * @example A simple selector to find an element by id. - *
- * var l0 = $('#myElementId');
- *
- *
- * @example You can pass an object reference to create a list containing only this element:
- *
- * var l1 = $(document.getElementById('myElementId'));
- *
- *
- * @example Lists and arrays will be copied:
- * - * var l2 = $([elementA, elementB, elementC]); - *- * - * @example Lists will be automatically flattened and nulls removed. So this list l3 has the same content as l2: - *
- * var l3 = $([elementA, [elementB, null, elementC], null]); - *- * - * @example This is a simple selector to find all elements with the given class. - *
- * var l4 = $('.myClass');
- *
- *
- * @example A selector to find all elements of the given type.
- *
- * var l5 = $('input'); // finds all input elements
- *
- *
- * @example A selector to find all elements with the given type and class.
- *
- * var l6 = $('input.myRadio'); // finds all input elements with class 'myRadio'
- *
- *
- * @example A selector to find all elements that are descendants of the given element.
- *
- * var l7 = $('#myForm input'); // finds all input elements contained in the element myForm
- *
- *
- * @example A selector to find all elements that have either a CSS class 'a' or class 'b':
- *
- * var l8 = $('.a, .b'); // finds all elements that have class a or class b
- *
- *
- * @example A selector that finds all elements that are descendants of the element myDivision, are inside an element with the
- * class .myForm and are input elements:
- *
- * var l9 = $('#myDivision .myForm input');
- *
- *
- * @example Contexts can make it easier to specify ancestors:
- *
- * var l10 = $('.myRadio', '#formA, #formB, #formC');
- *
- * The result is identical to:
- *
- * var l10 = $('#formA .myRadio, #formB .myRadio, #formC .myRadio');
- *
- *
- * @example Using one of the list functions, ##set(), on the list, and setting the element's text color. '$' at the beginning of the property name sets a CSS value.
- *
- * $('#myElementId').set('$color', 'red');
- *
- *
- * @example Most list methods return the list you invoked them on, allowing you to chain them:
- *
- * $('#myForm .myRadio').addClass('uncheckedRadio')
- * .set('checked', true)
- * .on('click', function() {
- * $(this).set({@: 'uncheckedRadio');
- * });
- *
- *
- * @example Using $() as a #ready#$.ready() shortcut:
- *
- * $(function() {
- * // in here you can safely work with the HTML document
- * });
- *
- *
- * @param selector a simple, CSS-like selector for HTML elements. It supports '#id' (lookup by id), '.class' (lookup by class),
- * 'element' (lookup by elements) and 'element.class' (combined class and element). Use commas to combine several selectors.
- * You can also join two or more selectors by space to find elements which are descendants of the previous selectors.
- * For example, use 'div' to find all div elements, '.header' to find all elements containing a class name called 'header', and
- * 'a.popup' for all a elements with the class 'popup'. To find all elements with 'header' or 'footer' class names,
- * write '.header, .footer'. To find all divs elements below the element with the id 'main', use '#main div'.
- * The selector "*" will return all elements.
- * @param list a list to copy. It can be an array, another Minified list, a DOM nodelist or anything else that has a length property and
- * allows read access by index. A shallow copy of the list will be returned. Nulls will be automatically removed from the copy. Nested lists
- * will be flattened, so the result only contains nodes.
- * @param object an object to create a single-element list containing only the object. If the argument is null, an empty list will be returned.
- * @param domreadyFunction a function to be registered using #ready#$.ready().
- * @param context optional an optional selector, node or list of nodes which specifies one or more common ancestor nodes for the selection. The context can be specified as
- * a selector, a list or using a single object, just like the first argument.
- * The returned list will contain only descendants of the context nodes. All others will be filtered out.
- * @param childOnly optional if set, only direct children of the context nodes are included in the list. Children of children will be filtered out. If omitted or not
- * true, all descendants of the context will be included.
- * @return the array-like ##list#Minified list## object containing the content specified by the selector.
- * Please note that if the first argument was a list, the existing order will be kept. If the first argument was a simple selector, the nodes are in document order.
- * If you combined several selectors using commas, only the individual results of the selectors will keep the document order,
- * but will then be joined to form a single list. This list will
- * not be in document order anymore, unless you use a build without legacy IE support.
- * Duplicate nodes will be removed from selectors, but not from lists.
- *
- * @see #underscore#_() is Util's alternative constructor for ##list#Minified lists##
- * @see ##dollardollar#$$()## works like $(), but returns the resulting list's first element.
- */
- '$': $,
-
- /*$
- * @id M
- * @name M
- * @syntax MINI.M
- * @module WEB, UTIL
- *
- * Exposes the internal class used by all ##list#Minified lists##. This is mainly intended to allow you adding your
- * own functions.
- *
- * @example Adding a function printLength() to M:
- *
- * MINI.M.prototype.printLength = function() { console.log(this.length); };
- *
- */
- 'M': M,
-
- /*$
- * @id getter
- * @requires get
- * @name MINI.getter
- * @syntax MINI.getter
- * @module WEB
- *
- * Exposes a map of prefix handlers used by ##get(). You can add support for a new prefix in get()
- * by adding a function to this map. The prefix can be any string consisting solely of non-alphanumeric characters
- * that's not already used by Minified.
- *
- * You must not replace getters by a new map, but must always modify the existing map.
- *
- * The function's signature is function(list, name) where
- *
- * MINI.getter['||'] = function(list, name) {
- * return list.get('$border' + name.replace(/^[a-z]/, function(a) { return a.toUpperCase()});
- * };
- *
- * var borderColor = $('#box').get('||color'); // same as '$borderColor'
- * var borderLeftRadius = $('#box').get('||leftRadius'); // same as '$borderLeftRadius'
- *
- *
- * @example Adding XLink attribute support to get(). This is useful if you work with SVG. The prefix is '>'.
- *
- * MINI.getter['>'] = function(list, name) {
- * return list[0].getAttributeNS('http://www.w3.org/1999/xlink', name);
- * };
- *
- * var xlinkHref = $('#svgLink').get('>href');
- *
- */
- 'getter': getter,
-
- /*$
- * @id setter
- * @requires set
- * @name MINI.setter
- * @syntax MINI.setter
- * @module WEB
- *
- * Exposes a map of prefix handlers used by ##set(). You can add support for a new prefix in set()
- * by adding a function to this map. The prefix can be any string consisting solely of non-alphanumeric characters
- * that's not already used by Minified.
- *
- * You must not replace setters by a new map, but must always modify the existing map.
- *
- * The function's signature is function(list, name, value) where
- *
- * MINI.setter['||'] = function(list, name, value) {
- * list.set('$border' + name.replace(/^[a-z]/, function(a) { return a.toUpperCase()}, value);
- * };
- *
- * $('#box').set('||color', 'red'); // same as set('$borderColor', 'red')
- * $('#box').set('||leftRadius', 4); // same as set('$borderLeftRadius', 4)
- *
- *
- * @example Adding XLink attribute support to set(). This is useful if you work with SVG. The prefix is '>'.
- *
- * MINI.setter['>'] = function(list, name, value) {
- * list.each(function(obj, index) {
- * var v;
- * if (_.isFunction(value))
- * v = value(obj.getAttributeNS('http://www.w3.org/1999/xlink', name), index, obj);
- * else
- * v = value;
- *
- * if (v == null)
- * obj.removeAttributeNS('http://www.w3.org/1999/xlink', name);
- * else
- * obj.setAttributeNS('http://www.w3.org/1999/xlink', name, v);
- * });
- * };
- *
- * $('#svgLink').set('>href', 'http://minifiedjs.com/');
- *
- */
- 'setter': setter
- /*$
- * @stop
- */
- ///#/snippet webExports
- };
-
- ///#snippet commonAmdEnd
-});
-///#/snippet commonAmdEnd
-///#snippet webDocs
-
-/*$
- * @id list
- * @name Minified Lists
- * @module WEB, UTIL
- *
- * Minified lists are Array-like objects provided by Minified. Like a regular JavaScript array,
- * they provide a length property and you can access their content using the index operator (a[5]).
- * However, they do not provide the same methods as JavaScript's native array and are designed to be immutable, so
- * there is no direct way to add something to a Minified list. Instead Minified provides a number of functions and methods
- * that take a list and create a modified copy which, for example, may contain additional elements.
- *
- * Minified lists are typically created either using the Web module's #dollar#$() function or with the Util module's
- * #underscore#_() function, but many functions in the Util module also return a Minified list.
- *
- * The Util module provides a function ##_.array() that converts a Minified list to a regular JavaScript array.
- */
-
-/*$
- * @id promiseClass
- * @name Promise
- * @module WEB, UTIL
- *
- * Promises are objects that represent the future result of an asynchronous operation. When you start such an operation, using #request#$.request(),
- * ##animate(), or ##wait(), you will get a Promise object that allows you to get the result as soon as the operation is finished.
- *
- * Minified's full distribution ships with a Promises/A+-compliant implementation of Promises that should
- * be able to interoperate with most other Promises implementations. Minified's Web module in stand-alone distribution comes with a limited implementation.
- * See below for details.
- *
- * What may be somewhat surprising about this Promises specification is that the only standard-compliant way to access the result is to
- * register callbacks. They will be invoked as soon as the operation is finished.
- * If the operation already ended when you register the callbacks, the callback will then just be called from the event loop as soon
- * as possible (but never while the ##then() you register them with is still running).
- * $.request('get', 'http://example.com/weather?zip=90210')
- * .then(function success(result) {
- * alert('The weather is ' + result);
- * }, function error(exception) {
- * alert('Something went wrong');
- * });
- *
- *
- * What makes Promises so special is that ##then() itself returns a new Promise, which is based on the Promise then() was called on, but can be
- * modified by the outcome of callbacks. Both arguments to then() are optional, and you can also write the code like this:
- *
- * $.request('get', 'http://example.com/weather?zip=90210')
- * .then(function success(result) {
- * alert('The weather is ' + result);
- * })
- * .then(null, function error(exception) {
- * alert('Something went wrong');
- * });
- *
- *
- * Because the first ##then() returns a new Promise based on the original Promise, the second then() will handle errors of the request just like
- * the first one did. There is only one subtle difference in the second example: the error handler will not only be called if the request failed,
- * but also when the request succeded but the success handler threw an exception. That's one of the two differences between the original Promise and
- * the Promise returned by then(). Any exception thrown in a callback causes the new Promise to be in error state.
- *
- * Before I show you the second difference between the original Promise and the new Promise, let me make the example a bit more readable
- * by using ##error(), which is not part of Promises/A+, but a simple extension by Minified. It just registers the failure callback without
- * forcing you to specify null as first argument:
- *
- * $.request('get', 'http://example.com/weather?zip=90210')
- * .then(function success(result) {
- * alert('The weather is ' + result);
- * })
- * .error(function error(exception) { // error(callback) is equivalent to then(null, callback)
- * alert('Something went wrong');
- * });
- *
- *
- * A very powerful capability of Promises is that you can easily chain them. If a ##then() callback returns a value, the new Promise returned
- * by then() will be marked as success (fulfilled) and this value is the result of the operation. If a callback returns a Promise,
- * the new Promise will assume the state of the returned Promise. You can use the latter to create chains of asynchronous operations,
- * but you still need only a single error handler for all of them and you do not need to nest functions to achieve this:
- *
- * $.request('get', 'http://example.com/zipcode?location=Beverly+Hills,+CA')
- * .then(function(resultZip) {
- * return $.request('get', 'http://example.com/weather', {zip: resultZip});
- * })
- * .then(function(resultWeather) {
- * alert('The weather in Beverly Hills is ' + resultWeather);
- * })
- * .error(function(exception) {
- * alert('Something went wrong');
- * });
- *
- *
- * Only the full Minified distribution allows you to create promises yourself, using the ##promise() function. The Promises/A+
- * specification does not specify how to fulfill a promise, but in Minified's implementation every Promise object has a function fire()
- * that needs to be called when the promise result is ready. It requires two arguments.
- * The first is a boolean, true for a successful operation and false for a failure. The second is an array or list containing the
- * arguments to call the corresponding ##then() handler with.
- *
- * The following example is a function, similar to ##wait(), that returns a Promise which succeeds after the given amount
- * of milliseconds has passed.
- * It then fulfills the promise with the number of milliseconds as argument.
- *
- *
- * function timeout(durationMs) {
- * var p = _.promise();
- * setTimeout(function() { p.fire(true, [durationMs]); }, durationMs);
- * return p;
- * }
- *
- * Call it like this:
- *
- * timeout(1000).then(function(ms) { window.alert(ms+ ' milliseconds have passed.'); });
- *
- *
- *