pulp javascript Examples and Usage
Below is a list of pulp's core modules with examples and common methods.
^topajax
Classic API examples
// simple request Ajax.request({ url: 'ajaxy.php', params: {dostuff: 1}, onComplete: myCompleteFn }); // updater request Ajax.request({ url: 'ajaxy.php', type: 'updater', container: 'mydiv', params: 'dostuff=1', onSuccess: mySuccessFn, on404: my404Fn, onFailure: myFailureFn });
Object data and inline callbacks
new Ajax('http://domain.com/ajaxy/', {nick: 'John100', searchTerm: 'Peanut Butter'}, { onSuccess: displayResults, onError: notifyOfError }).send();
String data and timeout option
new AjaxUpdater().send('http://domain.com/ajaxy/', 'nick=John100&searchTerm=Peanut Butter', { timeout: 10, // seconds after which to abort method: 'POST' onComplete: function(transport) { // ... do something } });
observers and object-oriented reuse
var ajax = new AjaxJson(url, params); ajax.on('complete', function(transport) { doStuff(transport.responseObject.myServerVars); }); ajax.send(); ajax.setData(newParams); ajax.send();
^toparray
Simple iteration
$A(['fruits', 'vegetables', 'meat']).each(function(food) { if (food != 'vegetables') { this.displayMessage('I like ' + food); } }, this);
Building values through inject
var checksum = $A([4, 1, 8, 6, 5, 0, 9]).inject(0, function(digit) { memo += digit * ((i % 2) + 1); return memo; });
Ability to pass a space-separated string
$A('a b c a d a g').unique().raw; // ['a', 'b', 'c', 'd', 'g']
Search, utilities, native Array methods
$A('zero one two three four').indexOf('two'); // 2 $A('one eight-hundred four six five').find(function(word) { return (word.substring(0, 1) == 'f'); }); // 'four' $A('one eight-hundred four six five').findIndex(function(word) { return (word.substring(0, 1) == 'f'); }); // 2 $A([1, 42, -3, 6]).min(); // -3 $A([1, 42, -3, 6]).max(); // 42 var shows = $A(); shows.push('Pushing Daisies'); shows.unshift('Burn Notice'); shows.push('Monk'); shows.concat(['Numb3rs', 'Psych']); shows.join(', '); // 'Burn Notice, Pushing Daisies, Monk, Numb3rs, Psych'
^topcls
Class creation
var Die = Class.create(); var SixSidedDie = Class.create(Die); var FourSidedDie = Die.createSubclass(); Die.subclasses; // [SixSidedDie, FourSidedDie] // mixins var FaceCard = Class.create(Card, { isRoyal: function() { return this.value == 'Q' || this.value == 'K'; } }, { isMale: function() { return this.value == 'J' || this.value == 'K'; } }, { wild: 'J' });
Inheritance and extensions
var Card = Class.create({ dimensions: [50, 100], initialize: function(value) { this.value = value; }, render: function() { return '<div class="card">' + this.value + '</div>'; } }); var Board = Class.create({ initialize: function() { this.html = ''; this.value = null; }, add: function(html) { this.html += html; } }); var Spade = Card.createSubclass({ suit: 'spade', breaksHearts: function() { return this.value == 'Q'; } }); Class.Base.prototype.pwn = function() { alert('pwnd'); }; Spade.prototype.pwn === Class.Base.prototype.pwn; // true new Spade().dimensions; // [50, 100] Card.extendPrototype({ play: function(board) { board.add(this.render()); } }); var board = new Board(); new Spade(2).play(board); Class.Base.addMethods({ toValue: function(o) { return o.value; } }); new Card('K').toValue(); // 'K' new Spade('K').toValue(); // 'K'
callParent() and applyParent()
var id = 0; var Grid = Class.create({ initialize: function(container) { this.container = container; this.id = ++id; }, setTitle: function(title, subtitle) { this.title = title; this.subtitle = subtitle; } }); var IpeGrid = Class.create(Grid, { initialize: function(container, options) { this.options = options || {}; this.callParent('initialize', container); }, setTitle: function(title, subtitle, instructions) { this.instructions = instructions; this.applyParent('setTitle', arguments); } });
^topcls.event
Cancel default actions
var Die = Class.create({ roll: function(player) { this.notify('roll', function(event) { this.value = randomWholeNumber(this.min, this.max); this.addToHistory(this.value); event.moreData = 'test'; }, {oldValue: this.value, player: player}); }, addToHistory: function(value) { this.cache.push(value); } }); var SixSidedDie = Class.create(Die, { min: 1, max: 6 }); var monopolyDie = new SixSidedDie(); monopolyDie.on('roll', function(event) { if (event.player.loseTurn) { event.preventDefault(); } }); monopolyDie.after('roll', function(event) { if (this.value > 6) { alert('hey, you cheated!'); } event.player.moreData == 'test'; // true });
Child class simplifies by observing itself
pulp.ajax.updater = pulp.ajax.createSubclass({ /** * Call parent constructor and observe complete callback * that sets options.container's innerHTML */ initialize: function(/*url, data, options*/) { this.applyParent('initialize', arguments); this.after('complete', function(event) { var t = this.transport, div; if (typeof this.options.container == 'string') { div = document.getElementById(this.options.container); } else if (this.options.container && this.options.container.nodeType == 1) { div = this.options.container; } (div || document.body).innerHTML = t.isSuccessful() ? t.responseText : (this.options.defaultText || ''); }); } });
^topcreateElement
Tag Name
var myLink = $E('a', { href: myUrl, 'class': 'popup', title: 'testing' }, 'Click Here!'); var myP = $E('p', null, myLink); document.appendChild(myP);
HTML Snippet
var myTd = $E('<td valign="top" colspan="2"></td>', 'Some data'); var myRow = $E('tr', null, myTd); myTable.appendChild(myRow);
^topcssQuery
Simple queries
var featuredDivs = $css('div.featured'); var disabledInputs = $css('input:disabled'); var firstParagraphs = $css('h1 + *'); var lastMenuItems = $css('ul.nav li:last-child'); var middleMenuItems = $css('ul.nav li:not(:first-of-type):not(:last-of-type)'); var externalLinks = $css('a:not([href^="http://mydomain.com"])');
Queries relative to another node
var divsInsideMyDiv = $css('div', myDiv); var psNextToMyP = $css('~ p', myP);
Custom Objects
var TabPopulator = function(targetNode) { this.setupUpdaters = function() { var i = 0, node; while ((node = this[i++])) { $(node).observe('click', function(evt) { evt.stop(); Ajax.request({ url: 'getContent.php', params: {href: this.href}, container: targetNode }); }); } }; }; var myTabs = new TabPopulator('info-window'); $css('a.tabber', null, myTabs); myTabs.setupUpdaters();
^topdate
Parse and format
$D('2/5/09').strftime('%B %e%o, %Y'); // February 5th, 2009 $D('2006-01-01').strftime('%b %e, %Y'); // Jan 1, 2009 $D('1 Jan 2009 7pm').strftime('%b %e, %Y %H:%M'); // Jan 1, 2009 19:00 $D('31.12.2008 15:00').strftime('%Y-%m-%d %H:%M:%S'); // 2008-12-31 15:00:00
Add/Subtract
$D('Oct 27, 2007').add(4, 'year'); // 2011-10-27 $D('Feb 11, 2008').add(-2, 'months'); // 2007-12-11 $D('Oct 26, 2007').add(2, 'days'); // 2007-10-28
Diff
$D('10/29/2007').diff('2007-10-31', 'day'); // -2 $D('10/29/2007').diff('2007-10-31'); // -2 $D('10/29/2007 23:30').diff('2007-10-29 23:00', 'hour', true); // 0.5
^topdate.extensions
Additional formatting
$D('2-5-09').phpFormat('n/j/Y g:ia'); // 2/5/2009 12:00am $D('1 Jan 2009 7pm').phpFormat('c'); // 2009-01-01T19:00:00 $D('June 13, 2008').phpFormat('ds \o\f F, Y'); // 13th of June, 2008
Creating a format plugin
pulp.date.phpFormat = { // // 2-part regex matcher for format codes // // first match must be the character before the code (to account for escaping) // second match must be the format code character(s) // matcher: /(^|[^\\])([a-z])/i, codes: { // year Y: 'FullYear', y: 'ShortYear.2', // month m: 'MonthNumber.2', // ... Z: 'GmtOffset' }, // // shortcuts that will be translated into their longer version // // be sure that format shortcuts do not refer to themselves: this will cause an infinite loop // shortcuts: { c: 'Y-m-d\TH:i:s', // ISO 8601 r: 'D, j d M Y H:i:s p' // RFC 2822 } }; // add the name of the static property and isntance method // and the default format to use when no arguments are passed pulp.date.addFormatter('phpFormat', 'Y-m-d');
Add a parser function or array
// 5 months ago, 2 hours ago, etc. (already included in pulp.date.extensions) pulp.date.patterns.ago = function (str) { var match = str.match( /(a|[\d.]+)\s+(year|month|week|day|hour|minute|second)s?\s+ago/i ); if (match) { return $D().add(-1 * (parseFloat(match[1]) || 1), match[2]); } }; // World time, e.g. 31.1.1980 or 31.01.1980 (already included in pulp.date) pulp.date.patterns.world = [( /^(3[01]|[0-2]?\d)\s*\.\s*(1[0-2]|0?\d)\s*\.\s*([1-9]\d{3})$/ ), '$2/$1/$3'], // ^day ^month ^year // \1 \2 \3
^topevent
Stand-alone static method examples
$e.observe('myId', 'mouseenter', myDropDownMenu); $e.stopObserving(myNode, 'click', myPopup); $e.fire(myInput, 'blur'); $e.fire(myTextarea, 'keyup', {myProp: myData});
pulp.node instance method examples
$('myId').observe('mouseenter', myDropDownMenu); $(myNode).stopObserving('click', myPopup); $(myInput).fire('blur'); $(myTextarea).fire('keyup', {myProp: myData});
Static Event method
var myDropDownMenu = function(event) { // event is the native browser Event instance $e.stop(event); if ($e.isRightClick(event)) { // ... } else { // ... } };
Instance Event method
var myPopup = function(event) { event = new $e(event); event.stop(); var x = event.pointerX(); };
Handler Scope and Event#target
var myPopup = function(event) { // "event.target" is the actual node clicked/moused over/etc. // which might be a child of the node to which the handler is attached if (event.target.tagName.toLowerCase() == 'img') { event.target.src = 'images/info.png'; } else { // "this" is the node to which the handler is attached this.style.color = 'red'; } };
^topjson
Basic encoding
var mydata = {one: 1, two: 'b', three: [3, 'c']}; JSON.encode(mydata); // '{"one":1,"two":"b","three":[3,"c"]}'
Basic decoding
var mystring = '{"one":1,"two":"b","three":[3,"c"]}'; var mydata = JSON.decode(mystring); // {one: 1, two: 'b', three: [3, 'c']};
^topnode
Construction
$ = pulp.node.getInstance; // with id var node = $('my-node'); // with HTMLElement object $(document.getElementById('my-node')) === node; // with another pulp.node object $(node) === node; // with an html string $('<div id="my-other-node"></div>');
Native method examples
var node = $('my-node'); node.getElementsByTagName('a'); // array of pulp.node objects node.getElementsByClassName('external'); // array of pulp.node objects node.appendChild('node-id'); // chainable node.clone(); // new pulp.node object node.appendChild(nodeOrIdOrHtml); // pulp.node object
Custom method examples
node.show(); node.removeClass('cssClassName'); node.setStyle('font-weight: bold; border: 2px solid #aaa');
Methods added by pulp.cssQuery
node.select(cssSelector); // array or pulp.nodeList object containing pulp.node objects node.match(cssSelector); // true if element matches the selector
^topnodeList
Query Examples
var $$ = pulp.nodeList.getInstance; // all elements with class "accordian" having an ancestor with class "feature" $$('.feature .accordian'); // all elements with class "sub-menu" having an ancestor with id "nav" $$('#nav .sub-menu'); // same as $$('.submenu', document.getElementById('nav')) // all p elements immediately following h1 $$('h1 + p'); //