pulp javascript Examples and Usage

Below is a list of pulp's core modules with examples and common methods.

^topajax

Overview

Shortcut: var Ajax = pulp.ajax;

Instantiate: new Ajax()

Common Methods

  • new Ajax([url][, data][, options])
  • #send([url][, data][, options])
  • #setProperties([url][, data][, options])
  • #observe(eventName, callback)

Full Documentation...

Distinguishing Features

  • Allows attaching multiple observers to each event (uninitialized, loading, loaded, interactive, complete, success, failure, abort, exception, beforeSend ,afterSend)
  • Allows attaching initial observers in options (e.g. onSuccess, onException)
  • Configurable timeout
  • Handles and reports back on various cases of dropped connections
  • Handles local files
  • Includes subclasses for handling JSON, XML, form serialization, and html updates
  • Reuses XMLHTTPRequest objects to save memory usage
  • Object-oriented API

Classic API examples

  1. // simple request
  2. Ajax.request({
  3. url: 'ajaxy.php',
  4. params: {dostuff: 1},
  5. onComplete: myCompleteFn
  6. });
  7. // updater request
  8. Ajax.request({
  9. url: 'ajaxy.php',
  10. type: 'updater',
  11. container: 'mydiv',
  12. params: 'dostuff=1',
  13. onSuccess: mySuccessFn,
  14. on404: my404Fn,
  15. onFailure: myFailureFn
  16. });

Object data and inline callbacks

  1. new Ajax('http://domain.com/ajaxy/', {nick: 'John100', searchTerm: 'Peanut Butter'}, {
  2. onSuccess: displayResults,
  3. onError: notifyOfError
  4. }).send();

String data and timeout option

  1. new AjaxUpdater().send('http://domain.com/ajaxy/', 'nick=John100&searchTerm=Peanut Butter', {
  2. timeout: 10, // seconds after which to abort
  3. method: 'POST'
  4. onComplete: function(transport) {
  5. // ... do something
  6. }
  7. });

observers and object-oriented reuse

  1. var ajax = new AjaxJson(url, params);
  2. ajax.on('complete', function(transport) {
  3. doStuff(transport.responseObject.myServerVars);
  4. });
  5. ajax.send();
  6. ajax.setData(newParams);
  7. ajax.send();

^toparray

Overview

Shortcut: var $A = pulp.array.getInstance;

Common Methods

  • $A([iterable])
  • #each(callback[, context])
  • #invoke(methodName[, arg1][, arg2][, argN])
  • #unique()
  • #inject(startValue, callback[, context])
  • #find(callback[, context])
  • #findIndex(callback[, context])
  • #indexOf(value)

Full Documentation...

Distinguishing Features

  • Can be constructed with a space delimited string, Array, nodeList, arguments object, or any other iterable object
  • Does not extend Array.prototype unless pulp.array.extendPrototype() is called
  • Same API as Array with methods such as push, concat, slice, splice and join
  • Conforms to ECMA Script 5 method names and supports a third argument for iteration
  • Uses for loops within every function to increase speed
  • Allows exiting a loop by throwing pulp.Break
  • Uses native forEach and indexOf functions when available

Simple iteration

  1. $A(['fruits', 'vegetables', 'meat']).each(function(food) {
  2. if (food != 'vegetables') {
  3. this.displayMessage('I like ' + food);
  4. }
  5. }, this);

Building values through inject

  1. var checksum = $A([4, 1, 8, 6, 5, 0, 9]).inject(0, function(digit) {
  2. memo += digit * ((i % 2) + 1);
  3. return memo;
  4. });

Ability to pass a space-separated string

  1. $A('a b c a d a g').unique().raw; // ['a', 'b', 'c', 'd', 'g']

Search, utilities, native Array methods

  1. $A('zero one two three four').indexOf('two'); // 2
  2. $A('one eight-hundred four six five').find(function(word) {
  3. return (word.substring(0, 1) == 'f');
  4. }); // 'four'
  5. $A('one eight-hundred four six five').findIndex(function(word) {
  6. return (word.substring(0, 1) == 'f');
  7. }); // 2
  8. $A([1, 42, -3, 6]).min(); // -3
  9. $A([1, 42, -3, 6]).max(); // 42
  10. var shows = $A();
  11. shows.push('Pushing Daisies');
  12. shows.unshift('Burn Notice');
  13. shows.push('Monk');
  14. shows.concat(['Numb3rs', 'Psych']);
  15. shows.join(', '); // 'Burn Notice, Pushing Daisies, Monk, Numb3rs, Psych'

^topcls

Overview

Create classes using Prototypal inheritance

Shortcut: var Class = pulp.cls;

Common Methods

  • Class.create([methods1][, methods2])
  • Class.create(parentClass, mixinClass1][, mixinClass2][, methods1][, methods2])
  • Class.create(constructor)
  • MyClass.createSubclass([, mixinClass1][, mixinClass2][, methods1][, methods2])
  • MyClass.alias(pairs)
  • MyClass.extend()
  • MyClass.extendPrototype()
  • MyClass.addMethods()

Full Documentation...

Distinguishing Features

  • Uses standard prototypal inheritance
  • Prototypal inherintance allows developers to exend all existing and future classes with #addMethods() and other extension methods
  • Prototypal inherintance allows calling parent class methods through instance.callParent() and instance.applyParent()
  • Prototypal inherintance is faster than manually extending prototypes
  • Adds methods to all classes including createSubclass, alias, aliasMethods, extend, extendPrototype

Class creation

  1. var Die = Class.create();
  2. var SixSidedDie = Class.create(Die);
  3. var FourSidedDie = Die.createSubclass();
  4. Die.subclasses; // [SixSidedDie, FourSidedDie]
  5. // mixins
  6. var FaceCard = Class.create(Card, {
  7. isRoyal: function() {
  8. return this.value == 'Q' || this.value == 'K';
  9. }
  10. }, {
  11. isMale: function() {
  12. return this.value == 'J' || this.value == 'K';
  13. }
  14. }, { wild: 'J' });

Inheritance and extensions

  1. var Card = Class.create({
  2. dimensions: [50, 100],
  3. initialize: function(value) {
  4. this.value = value;
  5. },
  6. render: function() {
  7. return '<div class="card">' + this.value + '</div>';
  8. }
  9. });
  10. var Board = Class.create({
  11. initialize: function() {
  12. this.html = '';
  13. this.value = null;
  14. },
  15. add: function(html) {
  16. this.html += html;
  17. }
  18. });
  19. var Spade = Card.createSubclass({
  20. suit: 'spade',
  21. breaksHearts: function() {
  22. return this.value == 'Q';
  23. }
  24. });
  25. Class.Base.prototype.pwn = function() { alert('pwnd'); };
  26. Spade.prototype.pwn === Class.Base.prototype.pwn; // true
  27. new Spade().dimensions; // [50, 100]
  28.  
  29. Card.extendPrototype({
  30. play: function(board) {
  31. board.add(this.render());
  32. }
  33. });
  34. var board = new Board();
  35. new Spade(2).play(board);
  36.  
  37. Class.Base.addMethods({
  38. toValue: function(o) {
  39. return o.value;
  40. }
  41. });
  42. new Card('K').toValue(); // 'K'
  43. new Spade('K').toValue(); // 'K'

callParent() and applyParent()

  1. var id = 0;
  2. var Grid = Class.create({
  3. initialize: function(container) {
  4. this.container = container;
  5. this.id = ++id;
  6. },
  7. setTitle: function(title, subtitle) {
  8. this.title = title;
  9. this.subtitle = subtitle;
  10. }
  11. });
  12. var IpeGrid = Class.create(Grid, {
  13. initialize: function(container, options) {
  14. this.options = options || {};
  15. this.callParent('initialize', container);
  16. },
  17. setTitle: function(title, subtitle, instructions) {
  18. this.instructions = instructions;
  19. this.applyParent('setTitle', arguments);
  20. }
  21. });

^topcls.event

Overview

Adds object observer methods to all classes.

Common Methods

  • #on(eventType, handler)
  • #after(eventType, handler)
  • #un(eventType, handler)
  • #notify(eventType[, defaultAction][, passData])

Full Documentation...

Distinguishing Features

  • Allows bubbling and cancelling default action

Cancel default actions

  1. var Die = Class.create({
  2. roll: function(player) {
  3. this.notify('roll', function(event) {
  4. this.value = randomWholeNumber(this.min, this.max);
  5. this.addToHistory(this.value);
  6. event.moreData = 'test';
  7. }, {oldValue: this.value, player: player});
  8. },
  9. addToHistory: function(value) {
  10. this.cache.push(value);
  11. }
  12. });
  13. var SixSidedDie = Class.create(Die, {
  14. min: 1,
  15. max: 6
  16. });
  17.  
  18. var monopolyDie = new SixSidedDie();
  19. monopolyDie.on('roll', function(event) {
  20. if (event.player.loseTurn) {
  21. event.preventDefault();
  22. }
  23. });
  24. monopolyDie.after('roll', function(event) {
  25. if (this.value > 6) {
  26. alert('hey, you cheated!');
  27. }
  28. event.player.moreData == 'test'; // true
  29. });

Child class simplifies by observing itself

  1. pulp.ajax.updater = pulp.ajax.createSubclass({
  2. /**
  3.   * Call parent constructor and observe complete callback
  4.   * that sets options.container's innerHTML
  5.   */
  6. initialize: function(/*url, data, options*/) {
  7. this.applyParent('initialize', arguments);
  8. this.after('complete', function(event) {
  9. var t = this.transport, div;
  10. if (typeof this.options.container == 'string') {
  11. div = document.getElementById(this.options.container);
  12. }
  13. else if (this.options.container && this.options.container.nodeType == 1) {
  14. div = this.options.container;
  15. }
  16. (div || document.body).innerHTML = t.isSuccessful() ?
  17. t.responseText :
  18. (this.options.defaultText || '');
  19. });
  20. }
  21. });

^topcreateElement

Overview

Quickly create HTMLElement objects.

Shortcut: var $E = pulp.createElement;

Common Methods

  • $E(tagOrHtml[, properties][, childNode])
  • $E(tagOrHtml[, properties][, childrenArray])
  • $E(tagOrHtml[, properties][, html])
  • $E(tagOrHtml[, properties][, HTMLNodeList])

Full Documentation...

Distinguishing features

  • Can receive a tag name or html string
  • When html string creates multiple elements, a wrapping div is returned
  • Children can be html, node list, node or pulp.node instance
  • Returns a pulp.node instance if pulp.node is available
  • Attributes are reliably set across browsers (IE6+, FF3+, Safari 3+, Chrome 1+, Opera 9+)

Tag Name

  1. var myLink = $E('a', {
  2. href: myUrl,
  3. 'class': 'popup',
  4. title: 'testing'
  5. }, 'Click Here!');
  6. var myP = $E('p', null, myLink);
  7. document.appendChild(myP);

HTML Snippet

  1. var myTd = $E('<td valign="top" colspan="2"></td>', 'Some data');
  2. var myRow = $E('tr', null, myTd);
  3. myTable.appendChild(myRow);

^topcssQuery

Overview

Retreive an array of DOM elements matching the given css selector.

Shortcut: var $css = pulp.cssQuery;

Common Methods

  • $css(selector[, fromElement=document][, addToObject]) -> Array
  • $css.match(element, selector) -> Boolean

Full Documentation...

Distinguishing features

  • Extremely fast and accurate using Diego Perini's NWMatcher Selector Engine. (Speed tests)
  • Supports the latest CSS3 syntax
  • Includes optimization for element.match(selector) usage
  • Intelligently caches results
  • Works reliably across browsers (IE6+, FF3+, Safari 3+, Chrome 1+, Opera 9+)
  • Allows starting selectors with >, + and ~ to indicate direct child, adjacent sibling and sibling relationships respectively
  • Allows passing a custom object or array to which to add results

Simple queries

  1. var featuredDivs = $css('div.featured');
  2. var disabledInputs = $css('input:disabled');
  3. var firstParagraphs = $css('h1 + *');
  4. var lastMenuItems = $css('ul.nav li:last-child');
  5. var middleMenuItems = $css('ul.nav li:not(:first-of-type):not(:last-of-type)');
  6. var externalLinks = $css('a:not([href^="http://mydomain.com"])');

Queries relative to another node

  1. var divsInsideMyDiv = $css('div', myDiv);
  2. var psNextToMyP = $css('~ p', myP);

Custom Objects

  1. var TabPopulator = function(targetNode) {
  2. this.setupUpdaters = function() {
  3. var i = 0, node;
  4. while ((node = this[i++])) {
  5. $(node).observe('click', function(evt) {
  6. evt.stop();
  7. Ajax.request({
  8. url: 'getContent.php',
  9. params: {href: this.href},
  10. container: targetNode
  11. });
  12. });
  13. }
  14. };
  15. };
  16. var myTabs = new TabPopulator('info-window');
  17. $css('a.tabber', null, myTabs);
  18. myTabs.setupUpdaters();

^topdate

Overview

Parse, format, add and compare dates.

Shortcut: var $D = pulp.date.getInstance;

Common Methods

  • $D(dateString)
  • #strftime(code)
  • #add(amount[, units=secods])
  • #diff(date2[, units=days][, allowDecimal=false])

Full Documentation...

Distinguishing features

  • Fast because it uses native browser Date.parse() function as much as possible
  • Easily extendible to recognize different formats
  • Easily extendible to output dates using different format codes
  • Allows shortcut codes (i.e. one symbol that represents a group of symbols)
  • All format strings can be set to allow translations

Parse and format

  1. $D('2/5/09').strftime('%B %e%o, %Y'); // February 5th, 2009
  2. $D('2006-01-01').strftime('%b %e, %Y'); // Jan 1, 2009
  3. $D('1 Jan 2009 7pm').strftime('%b %e, %Y %H:%M'); // Jan 1, 2009 19:00
  4. $D('31.12.2008 15:00').strftime('%Y-%m-%d %H:%M:%S'); // 2008-12-31 15:00:00

Add/Subtract

  1. $D('Oct 27, 2007').add(4, 'year'); // 2011-10-27
  2. $D('Feb 11, 2008').add(-2, 'months'); // 2007-12-11
  3. $D('Oct 26, 2007').add(2, 'days'); // 2007-10-28

Diff

  1. $D('10/29/2007').diff('2007-10-31', 'day'); // -2
  2. $D('10/29/2007').diff('2007-10-31'); // -2
  3. $D('10/29/2007 23:30').diff('2007-10-29 23:00', 'hour', true); // 0.5

^topdate.extensions

Overview

Adds more date parsing and formatting capabilities to pulp.date.

Additional parsing support

  • 3 years ago; 12 minutes ago; a day ago; etc.
  • 2 weeks after Jan 1, 2009; 2 days before 9/11/2001; 2 months before today; a week from yesterday; etc.
  • today; tomorrow; yesterday
  • this month; next year; last week; etc.

Additional formatting support

  • php format; e.g. Y-m-d H:i:s
  • sql format; e.g. yyyy-mm-dd

Additional formatting

  1. $D('2-5-09').phpFormat('n/j/Y g:ia'); // 2/5/2009 12:00am
  2. $D('1 Jan 2009 7pm').phpFormat('c'); // 2009-01-01T19:00:00
  3. $D('June 13, 2008').phpFormat('ds \o\f F, Y'); // 13th of June, 2008

Creating a format plugin

  1. pulp.date.phpFormat = {
  2. //
  3. // 2-part regex matcher for format codes
  4. //
  5. // first match must be the character before the code (to account for escaping)
  6. // second match must be the format code character(s)
  7. //
  8. matcher: /(^|[^\\])([a-z])/i,
  9.  
  10. codes: {
  11. // year
  12. Y: 'FullYear',
  13. y: 'ShortYear.2',
  14. // month
  15. m: 'MonthNumber.2',
  16. // ...
  17. Z: 'GmtOffset'
  18. },
  19. //
  20. // shortcuts that will be translated into their longer version
  21. //
  22. // be sure that format shortcuts do not refer to themselves: this will cause an infinite loop
  23. //
  24. shortcuts: {
  25. c: 'Y-m-d\TH:i:s', // ISO 8601
  26. r: 'D, j d M Y H:i:s p' // RFC 2822
  27. }
  28. };
  29. // add the name of the static property and isntance method
  30. // and the default format to use when no arguments are passed
  31. pulp.date.addFormatter('phpFormat', 'Y-m-d');

Add a parser function or array

  1. // 5 months ago, 2 hours ago, etc. (already included in pulp.date.extensions)
  2. pulp.date.patterns.ago =
  3. function (str) {
  4. var match = str.match( /(a|[\d.]+)\s+(year|month|week|day|hour|minute|second)s?\s+ago/i );
  5. if (match) {
  6. return $D().add(-1 * (parseFloat(match[1]) || 1), match[2]);
  7. }
  8. };
  9. // World time, e.g. 31.1.1980 or 31.01.1980 (already included in pulp.date)
  10. pulp.date.patterns.world =
  11. [( /^(3[01]|[0-2]?\d)\s*\.\s*(1[0-2]|0?\d)\s*\.\s*([1-9]\d{3})$/ ), '$2/$1/$3'],
  12. // ^day ^month ^year
  13. // \1 \2 \3

^topevent

Overview

Shortcut: var $e = pulp.node;

Use with pulp.node: $(id).observe(...)

Common Methods

  • observe(node, type, handler)
  • stopObserving(node, type, handler)
  • fire(node, type[, data])

Preferred API when pulp.node is available

  • $(id).observe(type, handler)
  • $(id).stopObserving(type, handler)
  • $(id).fire(type[, data])

Full Documentation...

Distinguishing Features

  • Allows modular architecture to make it easy to define custom DOM events such as mouseenter, key:idle, ctrl+click, ctrl+A, etc.
  • Allows adding custom Event instance methods such as getWheelDirection()
  • Fixes event Event#target and scope for IE events

Stand-alone static method examples

  1. $e.observe('myId', 'mouseenter', myDropDownMenu);
  2. $e.stopObserving(myNode, 'click', myPopup);
  3. $e.fire(myInput, 'blur');
  4. $e.fire(myTextarea, 'keyup', {myProp: myData});

pulp.node instance method examples

  1. $('myId').observe('mouseenter', myDropDownMenu);
  2. $(myNode).stopObserving('click', myPopup);
  3. $(myInput).fire('blur');
  4. $(myTextarea).fire('keyup', {myProp: myData});

Static Event method

  1. var myDropDownMenu = function(event) { // event is the native browser Event instance
  2. $e.stop(event);
  3. if ($e.isRightClick(event)) {
  4. // ...
  5. }
  6. else {
  7. // ...
  8. }
  9. };

Instance Event method

  1. var myPopup = function(event) {
  2. event = new $e(event);
  3. event.stop();
  4. var x = event.pointerX();
  5. };

Handler Scope and Event#target

  1. var myPopup = function(event) {
  2. // "event.target" is the actual node clicked/moused over/etc.
  3. // which might be a child of the node to which the handler is attached
  4. if (event.target.tagName.toLowerCase() == 'img') {
  5. event.target.src = 'images/info.png';
  6. }
  7. else {
  8. // "this" is the node to which the handler is attached
  9. this.style.color = 'red';
  10. }
  11. };

^topjson

Overview

Shortcut: var JSON = pulp.json;

Methods

  • encode(object)
  • decode(string)

Full Documentation...

Distinguishing features

  • Fully spec compliant including preprocess function, reviver function and recursion check
  • Uses native browser implementation if it is spec compliant

Basic encoding

  1. var mydata = {one: 1, two: 'b', three: [3, 'c']};
  2. JSON.encode(mydata);
  3. // '{"one":1,"two":"b","three":[3,"c"]}'

Basic decoding

  1. var mystring = '{"one":1,"two":"b","three":[3,"c"]}';
  2. var mydata = JSON.decode(mystring);
  3. // {one: 1, two: 'b', three: [3, 'c']};

^topnode

Overview

Manipulate and traverse the DOM.

Shortcut: var $ = pulp.node.getInstance

Construction Options

  • $(elementId)
  • $(HTMLElement)
  • $(pulpNodeObject)
  • $(html)

Common Methods

  • setAttribute(name, value)
  • addClassName(name)
  • setStyle(name, value)
  • update(html)
  • hide()
  • up(selector)
  • down(selector)
  • getDimensions()

Full Documentation...

Distinguishing features

  • Can receive a tag name, html string, node or pulp.node object
  • Has all native HTMLElement methods
  • Fires dom:modified notifications
  • Reliable across browsers (IE6+, FF3+, Safari 3+, Chrome 1+, Opera 9+)

Construction

  1. $ = pulp.node.getInstance;
  2. // with id
  3. var node = $('my-node');
  4. // with HTMLElement object
  5. $(document.getElementById('my-node')) === node;
  6. // with another pulp.node object
  7. $(node) === node;
  8. // with an html string
  9. $('<div id="my-other-node"></div>');

Native method examples

  1. var node = $('my-node');
  2. node.getElementsByTagName('a'); // array of pulp.node objects
  3. node.getElementsByClassName('external'); // array of pulp.node objects
  4. node.appendChild('node-id'); // chainable
  5. node.clone(); // new pulp.node object
  6. node.appendChild(nodeOrIdOrHtml); // pulp.node object

Custom method examples

  1. node.show();
  2. node.removeClass('cssClassName');
  3. node.setStyle('font-weight: bold; border: 2px solid #aaa');

Methods added by pulp.cssQuery

  1. node.select(cssSelector); // array or pulp.nodeList object containing pulp.node objects
  2. node.match(cssSelector); // true if element matches the selector

^topnodeList

Overview

Query and manipulate a collection of pulp.node objects. A hybrid of jQuery and Prototype collections.

Shortcut: var $$ = pulp.nodeList.getInstance

Construction

  • $$(selector)
  • $$(selector, startingNode)

pulp.nodeList has all relavant methods of pulp.node

  • pulp.node methods that set properties and manipulate nodes operate on all nodes in the collection (e.g. setStyle(), update(), removeClass(), hide(), etc.)
  • pulp.node methods that return one or a list of nodes will return an array containing the combined results (e.g. getElementsByTagName(), cloneNode(), up(), select(), etc.)
  • pulp.node methods that return a value will return that value for the first node in the collection (e.g. identify(), getDimensions(), hasClassName(), etc.)

Additional Methods

  • $$(selector).delegate(eventName, handler)
  • $$(selector).stopDelegating(eventName, handler)
  • $$(selector).include(node)

Full Documentation...

Distinguishing features

  • Extremely fast and accurate using Diego Perini's NWMatcher Selector Engine. (Speed tests)
  • Supports the latest CSS3 syntax
  • Includes optimization for $$(selector).include(element) usage
  • Intelligently caches results
  • Allows query to be set without executing and thus facilitates efficient delegation

Query Examples

  1. var $$ = pulp.nodeList.getInstance;
  2.  
  3. // all elements with class "accordian" having an ancestor with class "feature"
  4. $$('.feature .accordian');
  5.  
  6. // all elements with class "sub-menu" having an ancestor with id "nav"
  7. $$('#nav .sub-menu'); // same as $$('.submenu', document.getElementById('nav'))
  8.  
  9. // all p elements immediately following h1
  10. $$('h1 + p');
  11.  
  12. //