About Snack

Snack API Documentation

Because sometimes, all you need is a snack.

Snack is a small and simple JavaScript library. Though ideal for small projects, it's got enough in it to build complex, cross-browser web apps. Visit the github repository for more information.

This documentation is released under the Creative Commons - Attribution-NonCommercial-ShareAlike license.

core

Object.create

Creates a new object with a defined prototype. Helpful for prototypal inheritance and object templating.

Signature

Object.create(obj)

Arguments

  1. obj (object) - The object to be used as the new object's prototype

Returns

Object - A new object

Examples

var dad = {
  cash: 'tons',
  init: function (name){
    this.name = name
  }
}

dad.init('Casey')
dad.name //> 'Casey'

var son = Object.create(dad)
son.name //> 'Casey'

son.init('Ryan')
son.name //> 'Ryan'

dad.cash //> 'tons'
son.cash //> 'tons' ... yes!

dad.cash = 'none'
son.cash //> 'none' ... hey, what the?!

// because dad is the prototype of son, it inherits dad's values

Notes

Object.create is part of the ES5 spec. This method is only implemented if it does not already exist in the environment. This implementation, however, does not support the second argument of the native Object.create method.

Implementation taken from Douglas Crockford's original version

See also: MDC Object.create

snack.extend

Performs a shallow merge of two or more objects into the first.

Signature

snack.extend(target [, obj1 [, objN]])
snack.extend(obj)

Arguments

  1. target (object) - The target object to receive the properties of subsequent objects.
  2. obj1 (object) - An object containing properties to merge into the target
  3. objN (object) - Additional object to merge into the target
  4. obj (object) - If only one object is provided, the target becomes the snack namespace, and the object is merged into it

Returns

Object - The target object

Examples

Extend an object

var coords = {
  x: 1,
  y: 1
}

snack.extend(coords, {
  translateY: function (amt){
    this.y += amt
  },
  translateX: function (amt){
    this.x += amt
  }
})

coords.translateY(10);
coords.y //> 11

Set options (typical of plugins)

var defaults = {
  foo: 1,
  bar: 'baz'
}

function init (options){
  var settings = snack.extend({}, defaults, options)
  // `options` overwrites `defaults`
  // and that is added to the empty {} object
  // which becomes `settings`, a brand new object baby
}

function badInit (options){
  options = snack.extend(defaults, options)
  // bad for this use case because defaults is overwritten
  // and next time it will contain everything in options :(
}

Extend snack

snack.extend({
  awesome: true
})

snack.awesome //> true, you know it

snack.bind

Binds the context of a function (this) to an object.

Signature

snack.bind(fn [, context [, args]])

Arguments

  1. fn (function) - The function to bind the context to.
  2. context (object) - The object to become the context of the function.
  3. args (array: optional) - An array of arguments to prepend to the existing arguments of the function.

Returns

Function - The bound function.

Examples

Binding handlers to object methods

var widget = {
  node: document.getElementById('some-el'),

  init: function (){
    this.listener = snack.listener(
      {node: this.node},
      snack.bind(this.handler, this, ['foo', 'bar']) // here!
    )
  },

  handler: function (foo, bar, event){
    // `this` is `widget`, instead of `node` (default context)
    // foo and bar are added before event
  }
}

snack.punch

Mutates an object method with new logic (Duck punching).

Signature

snack.punch(obj, method, fn [, auto])

Arguments

  1. obj (object) - The object who's method is getting punched.
  2. method (string) - The name of the object's method.
  3. fn (function) - The new function.

    Signature

    function ([old [, argN]])

    Arguments

    1. old (function) - The old version of the method, (with context already bound to the object). Note: This argument is passed by default, if the auto argument is used then this argument will not be passed
    2. argN (mixed) - Any arguments passed when the method is called.
  4. auto (boolean: optional, defaults to false) - If true, will automatically call the old method before calling the new one.

Returns

Undefined

Examples

var widget = {
  a: 0,
  b: 0,
  add: function (amt){
    this.a += amt
  }
}

widget.add(1)
widget.a //> 1
widget.b //> 0

snack.punch(widget, 'add', function (old, amt){
  // old is the old version of this method, already bound to widget
  // call it wherever you want inside of here
  old(amt)
  this.b += amt
})

widget.add(1)
widget.a //> 2
widget.b //> 1

snack.punch(widget, 'add', function (){
  // the last arg (`auto`) is `true`, so old will be called before
  // this stuff happens.  Effectively the same as calling `old`
  // on the first line of this new function.
  console.log("I'm adding stuff!")
}, true)

widget.add(1) // console logs "I'm adding stuff!"
widget.a //> 3
widget.b //> 2

snack.punch(widget, 'add', function (old){
  return this.a + this.b
  // since `auto` is not true, and old is not called
  // this method has been completely overwritten
})

var res = widget.add()
res //> 5
widget.a //> 3 ... unchanged
widget.b //> 2 ... unchanged

Notes

When using the auto argument, this is extremely similar to dojo.connect (minus the DOM events). It's also not unlike Extends and this.parent in a MooTools class. Think of the old argument as this.parent.

snack.create

Similar to Object.create, except it allows for an extension object to merge into the new object. When methods are redefined in the extension object, they are automatically punched providing a reference to the old (or parent) method. Useful for object templating and prototypal inheritance.

Signature

snack.create(proto [, ext])

Arguments

  1. proto (object) - The object use as the prototype.
  2. ext (object: optional) - An object to merge into the new object. Note: if a method is redefined then it will be automatically punched, providing as the first argument of the method the old method. Please see the examples.

Returns

Object - A new object with proto as its prototype and ext merged into it.

Examples

// create a generic object
var point = {
  coords: {
    x: 0,
    y: 0
  },

  translate: function (x, y){
    this.coords.x += x
    this.coords.y += y
  },

  sum: function (){
    var sum = 0
    snack.each(this.coords, function(key, value){
      sum += value
    })
    return sum
  }
}

// create a generic object that inherits from the other
var point3d = snack.create(point, {
  // new property
  z: 0,
  // redefined method
  translate: function (old, x, y, z){
    // if a method exists in the prototype object
    // then the method here is automatically punched
    // providing the old method as the first argument
    old()
    this.coords.z += z
  }
})

// create objects that inherit from the generic objects (instances, if you will)
var p = snack.create(point)
p.translate(5,10)
p.coords.x //> 5
p.coords.y //> 10
p.sum() //> 15
p.__proto__ === point //> true

var p3d = snack.create(point3d)
p3d.translate(1,2,3) // punched method, note that the signature does not
                     // include the `old` argument when being called
p.coords //> {x: 1, y: 2, z: 3}
p.sum() //> 6, inherited
p3d.__proto__ === point3d //> true

snack.id

Generates an incrementing global unique identifier

Signature

snack.id()

Returns

Number - A unique number

Examples

snack.id() //> 1
snack.id() //> 2

snack.each

Iterates over objects, arrays, and array-like objects.

Signature

snack.each(obj, fn [, context])

Arguments

  1. obj (mixed) - Accepts an object, array, or array-like object.
  2. fn (function) - The function to call for each property or element.

    Signature

    function (item, index, arr) // arrays
    function (value, key, obj) // objects

    Arguments

    1. item, value (mixed) - The current array item or object property's value.
    2. index, key (mixed) - The current array index or object property name.
    3. arr, obj (mixed) - The array or object.
  3. context (object: optional) - Context of the fn.

Returns

Mixed - The obj argument.

Examples

Arrays

var total = 0
snack.each([1,2,3], function (number){
  total += number
})
total //> 6

Objects

var numbers = {
  one: 1,
  two: 2,
  three: 3,
  total: null
}
snack.each(numbers, function (value, key){
  if (key == 'total')
    return
  numbers.total += value
})
numbers.total //> 6

Array-like objects

var fakeArray = {
  0: 1,
  1: 2,
  2: 3,
  length: 3
}
var total = 0
snack.each(fakeArray, function (number){
  total += number
})
total //> 6

Notes

If you're coming from jQuery, the signature for snack.each is reversed, and the context is not set to the item, following the native Array.prototype.forEach spec.

snack.parseJSON

Signature

snack.parseJSON(json)

Arguments

  1. json (json string) - A well-formed JSON string.

Returns

Object - The parsed JavaScript object

Examples

An XHR request with a JSON response

snack.request({url: '/tags/1'}, function (err, json){
  // json = '{"name":"foo", "_id":"4b5783300334000000000aa9"}'
  var data = snack.parseJSON(json)
  data.name //> foo
  data._id //> 4b5783300334000000000aa9
})

Notes

Code adapted from jQuery.parseJSON().

snack.isArray

Determines if an object is an array.

Signature

snack.isArray(obj)

Arguments

  1. obj (mixed) - The object to check

Returns

Boolean - True if the object is an array, false otherwise.

Examples

snack.isArray([1,2,3]) //> true
snack.isArray('') //> false
snack.isArray({}) //> false

Notes

typeof returns 'object' for arrays, making this method useful.

snack.indexOf

Cross-browser indexOf method to determine the index of an item in an array (or array-like object)

Signature

snack.indexOf(item, array)

Arguments

  1. item (mixed) - The array element for which to search.
  2. array (array) - The array to search.

Returns

Number - If found, returns the index, otherwise returns -1

Examples

Typical use

var arr = [1, 2, 3]
snack.indexOf(2, arr) //> 1
snack.indexOf(4, arr) //> -1

Extend the array prototype, if you're hard-core

if (![].indexOf){
  Array.prototype.indexOf = function (item){
    return snack.indexOf(item, this)
  }
}
[1,2,3].indexOf(1) //> 0

Notes

If the browser supports Array.prototype.indexOf, the native method is used.

wrap

snack.wrap

Wraps DOM elements into an array-like object with element based prototype methods.

Signature

snack.wrap(nodes)

Arguments

  1. nodes (mixed) - Accepts one or many DOM elements or a CSS selector string.

Returns

Object wrap - An array-like object with useful element methods

Examples

var divs     = snack.wrap('div.find_me') // CSS Selector
  , elements = snack.wrap(document.getElementsByTagName('div'))
  , d00d     = snack.wrap(document.getElementById('dude'))

divs[0]     //> first element in `divs`
elements[1] //> second element in `elements`, etc.

Notes

  • The CSS Selector you pass in to snack.wrap must be supported by the selector engine you're using.
  • snack allows you to define the selector engine you want to use. querySelectorAll is the default selector engine, supported by IE8+, and the real browsers.
  • If you need to support IE < 8 you should use one of the builds that includes a selector engine: qwery, slick, or sizzle. Alternatively, you can still select elements with getElementById, getElementsByTagName etc. and pass them in as the nodes argument. A selector engine is not required.
  • When Qwery matures, it is the suggested selector engine because its goals are similar to Snack's and results in a smaller file size. However, Qwery is still quite young, so if your code doesn't work in oldIE, try using a different selector engine before thinking it's snack's fault :D

wrap.each

Iterates over a collection of wrapped elements.

Signature

wrap.each(fn, context)

Arguments

  1. fn (function) - The function to call for each element.

    Signature

    function (item, index, wrap)

    Arguments

    1. item (element) - The current (unwrapped) DOM element.
    2. index (number) - The current array index or object property name.
    3. wrap (obj) - The wrap object.
  2. context (object: optional) - Context of the fn.

Returns

Object wrap

Examples

snack.wrap('div').each(function (element, index){
  var params = {node: element, event: 'click'}
  snack.listener(params, function (){
    alert(index)
  })
})

Notes

If you're coming from jQuery, the signature for wrap.each is reversed, and the context is not set to the item, following the native Array.prototype.forEach spec.

wrap.addClass

Adds a CSS class name from each element in the wrap.

Signature

wrap.addClass(className)

Arguments

  1. className (string) - A CSS class name, accepts multiple.

Returns

Object - wrap

Examples

snack.wrap('div').addClass('foo')
snack.wrap('a').addClass('bar baz') // can add multiple at once

wrap.removeClass

Removes a CSS class from each element in the wrap.

Signature

wrap.removeClass(className)

Arguments

  1. className (string) - A single class name to remove.

Returns

Object - wrap

Examples

var wrap = snack.wrap('div')
wrap.addClass('foo')

// later
wrap.removeClass('foo')

// put it back on the first element
snack.wrap(elements[0]).addClass('foo')

wrap.attach

Attaches an event handler to each element in the wrap.

Signature

wrap.attach(event, handler)

Arguments

  1. event (string) - The event handler to add, i.e. 'click'
  2. handler (function) - The event handler.

Returns

Object - wrap

Examples

var wrap = snack.wrap('#some-el')
wrap.attach('click', function (){
  // do something
})

wrap.detach

Detaches any event handlers added with a namespace from each element in the wrap.

Signature

wrap.detach(namespace)

Arguments

  1. namespace (string) - The namespace of events.

Returns

Object - wrap

Examples

var wrap = snack.wrap('#some-el')
wrap.attach('click.foo', function (event){
  // do something
})
wrap.attach('mouseover.foo', function (event){
    // do something else
})

// later
wrap.detach('foo') // removes both listeners

wrap.fire

Fires any event handlers added with a namespace for each element in the wrap.

Signature

wrap.fire(namespace)

Arguments

  1. namespace (string) - The namespace of events.

Returns

Object - wrap

Examples

var wrap = snack.wrap('#some-el')
wrap.attach('click.foo', function (event){
  // do something
})
wrap.attach('mouseover.foo', function (event){
  // do something else
})

wrap.fire('foo') // fires both listeners

wrap.data

Stores any JavaScript data with a specific wrapper.

Signature

wrap.data(key [, value])

Arguments

  1. key (string) - The key to store the data on.
  2. value (mixed) - Any type of data to store. If omitted, the data will be set.

Returns

Mixed - The value argument, whether used as a getter or setter.

Examples

Single element data

var wrap = snack.wrap('#some-el')
wrap.data('height', wrap[0].scrollHeight) //> returns the scrollHeight, let's say 100

// later
wrap.data('height') //> 100

Multiple element data

var wrap = snack.wrap('.some_els')

var heights = []
wrap.each(function (node){
  heights.push(node.scrollHeight)
})
wrap.data('heights', heights)

// in some other method outside the `heights` scope
// (otherwise, you wouldn't need data)
var heights = wrap.data('heights')
wrap.each(function (node, index){
  heights[index] //> the node's `scrollHeight`
})

Notes

This is not as useful as MooTools or jQuery's element storage since it belongs to a wrapper rather than an element, but it's still pretty useful.

snack.wrap.define

Defines a prototype method for wraps created with snack.wrap

Signature

snack.wrap.define(name, fn)
snack.wrap.define(methodsObject)

Arguments

  1. name (string) - The method name.
  2. fn (function) - The method function.
  3. methodsObject (object) - Object of name:fn pairs.

Returns

Undefined

Examples

Define a single method

snack.wrap.define('makeRed', function (){
  return this.each(function (element){
    element.style.color = 'red'
  })
})

var wrap = snack.wrap('div')
wrap.makeRed()

Define multiple methods

snack.wrap.define({
  hide: function (){
    return this.each(function (element){
      element.style.display = 'none'
    })
  },
  show: function (){
    return this.each(function (element){
      element.style.display = ''
    })
  }
})

els.hide()
els.show()

Notes

  • This is similar to using jQuery's jQuery.fn = function (){} or MooTools Element.implement(method, fn).
  • The context of the defined method is a wrap object.
  • Returning this or a method that returns this allows you to chain these methods together for a potentially miserable, but often pleasant API.

snack.wrap.defineEngine

Defines a selector engine for snack.wrap to use. The default engine is querySelectorAll

Signature

snack.wrap.defineEngine(fn)

Arguments

  1. fn (function) - A function that returns an element collection.

    Signature

    function (selector, context)

    Arguments

    1. selector (string) - A CSS selector string.
    2. context (mixed) - A DOM element or CSS selector string used as the context of the query.

    Returns

    Must return an element collection.

Returns

Undefined

Examples

// Use qwery
snack.wrap.defineEngine(function (selector, context){
  return qwery(selector, context);
})

// Use Slick
snack.wrap.defineEngine(function (selector, context){
  if (typeof context === 'string')
    context = Slick.search(document, context)[0]
  return Slick.search(context || document, selector)
})

// Use Sizzle
snack.wrap.defineEngine(function (selector, context){
  if (typeof context === 'string')
    context = Sizzle(context)[0]
  return Sizzle(selector, context)
})

// Or do everything by id
snack.wrap.defineEngine(function (selector, context){
  if (typeof context === 'string')
    context = document.getElementById(context)
  return [(context || document).getElementById(selector)] // return an array
})

Notes

event

snack.ready

Cross-browser DOMContentLoaded function.

Signature

snack.ready(handler)

Arguments

  1. handler (function) - The function to call when the dom is ready.

Returns

Undefined

Examples

snack.ready(function (){
  // do something
})

Notes

Adapted from Diego Perini's contentLoaded function.

snack.listener

Cross-browser DOM event listener.

Signature

snack.listener(params, handler)

Arguments

  1. params (object) - Key value pairs of parameters for the listener.
    • node (element) - A DOM element to attach the listener to.
    • event (string) - Which event to listen to, i.e. 'click'.
    • capture (boolean: default false) - Initiates capture. See http://www.w3.org/TR/DOM-Level-3-Events/#event-flow
    • delegate (mixed) - Accepts a CSS selector or a function

      Signature

      function (node)

      Arguments

      1. node (element) - The element the event is listening on

      Returns Array - You must return an element collection, or array of elements you want to be matched against the event.

  2. handler (function) - The event handler.

Returns

Object - A listener object.

Examples

A basic click listener

var params = {
  node: document.getElementById('foo'),
  event: 'click'
}
snack.listener(params, function (){
  alert('hey!')
})

Delegate with function

var params = {
  node: document.getElementById('foo'),
  event: 'click',
  delegate: function (node){
    // return a collection of elements
    // only buttons will fire the handler
    return node.getElementsByTagName('button')
  }
}

snack.listener(params, function (){
  alert('hey!')
})

Delegate with CSS selector

snack.listener({
  node: document.getElementById('foo'),
  event: 'click',
  delegate: 'button' // same as above but uses the selector engine
}, function (){
  alert('hey!')
})

Notes

See also wrap.attach.

listener.attach

Attaches the listener to the element (automatically called in snack.listener).

Signature

listener.attach()

Returns

Undefined

Examples

var listener = snack.listener({
  node: document.getElementById('foo'),
  event: 'click'
}, function (){
  alert('hey!')
})

listener.detach()
// click does nothing

listener.attach()
// click is attached again

listener.detach

Detaches the listener from the element.

Signature

listener.detach()

Returns

Undefined

Examples

var listener = snack.listener({
  node: document.getElementById('foo'),
  event: 'click'
}, function (){
  alert('hey!')
})

listener.detach()
// click does nothing

listener.attach()
// click is attached again

listener.fire

Fires the handler of a listener.

Signature

listener.fire([arg1, [argN]])

Arguments

  1. arg1 (mixed: optional) - An argument to be passed to the handler, often a mock event object should be supplied.
  2. argN (mixed: optional) - Any number of arguments passed in will be applied to the handler.

Returns

Undefined

Examples

var listener = snack.listener({
  node: document.getElementById('foo'),
  event: 'keyup'
}, function (event){
  event.keyCode //> 'fake'
})

listener.fire({keyCode: 'fake'})

snack.preventDefault

Cross-browser method to cancel an event without stopping further propagation of the event.

Signature

snack.preventDefault(event)

Arguments

  1. event (event) - A DOM event object

Returns

Undefined

Examples

snack.listener({
  event: 'click',
  node: document.getElementById('foo')
}, function (event){
  snack.preventDefault(event) // cancels event
})

Notes

See MDC event.preventDefault

snack.stopPropagation

Cross-browser method to prevent bubbling (propagation) of an event.

Signature

snack.stopPropagation(event)

Arguments

  1. event (event) - A DOM event object

Returns

Undefined

Examples

snack.listener({
  event: 'click',
  node: document.getElementById('foo')
}, function (event){
  snack.stopPropagation(event) // prevents bubbling
})

Notes

See MDC event.stopPropagation

publisher

snack.publisher

Turns any object into a "publisher", extending it with publish and subscribe methods, or creates a new generic publisher.

Signature

snack.publisher([obj])

Arguments

  1. obj (Object: optional) - The object to make a "publisher". If undefined, a generic publisher will be created.

Returns

Object - The obj supplied or a new publisher object.

Examples

Creating a generic publisher

var pubsub = snack.publisher()
  , c = 1

pubsub.subscribe('foo', function (amt){
  c += amt
})

pubsub.publish('foo', [10])
c //> 11

Extending an existing object

var coords = {
  x: 1,
  y: 1,
  translateY: function (amt){
    this.y += amt
    this.publish('translateY', [amt, this.y]) // publish the event
  },
  translateX: function (amt){
    this.x += amt
    this.publish('translateX', [amt, this.x]) // publish the event
  }
}

snack.publisher(coords) // turn coords into a publisher

var subscription = coords.subscribe('translateY', function (amt, y){
  console.log(amt, y)
})

coords.translateY(10) // console logs 10, 11

publisher.publish

Publishes an event with arguments, calling all subscription handlers.

Signature

publisher.publish(channel, argsArray)

Arguments

  1. channel (string) - The channel to publish.
  2. argsArray (array) - An array of arguments to apply to the subscription handlers.

Returns

Number - The number of subscription handlers called.

Examples

var megaphone = snack.publisher()

megaphone.subscribe('foo', function (data){
  console.log(data.awesome)
})

pubsub.subscribe('foo', function (data){
  console.log(data.lame)
})

snack.JSONP({url: '/items'}, function (data){
  var fired = megaphone.publish('jsonp/success', [data])
  fired //> 2, since we added two subscriptions
        // console logs data.awesome, data.lame, from the subscriptions above
})

publisher.subscribe

Adds a new subscription (event handler) to a publisher object.

Signature

publisher.subscribe(channel, handler [, context])

Arguments

  1. channel (string) - The channel to subscribe to.
  2. handler (function) - The handler to call when the channel is published. Arguments applied by the call to publish
  3. context (object: optional) - The context of handler

Returns

Undefined

Examples

var el = snack.wrap('#element')
  , el2 = snack.wrap('#el2')
  , pubsub = snack.publisher()

pubsub.subscribe('foo', function (){
  console.log(this) //> el
}, el)

pubsub.subscribe('foo', function (){
  console.log(this) // el2
}, el2)

pubsub.publish('foo')

Notes

subscription.attach

Attaches the subscription handler, to be called when published. Called automatically in publisher.subscribe

Signature

subscription.attach()

Returns

Undefined

Examples

var publisher = snack.publisher()
  , subscription = publisher.subscribe('foo', function (){
      console.log('hey there')
    })

subscription.detach()
publisher.publish('foo') // nothing happens

subscription.attach()
publisher.publish('foo') // stuff happens

subscription.detach

Detaches the subscription handler, preventing it from being called.

Signature

subscription.detach()

Returns

Undefined

Examples

var publisher = snack.publisher()
  , subscription = publisher.subscribe('foo', function (){
      console.log('hey there')
    })

subscription.detach()
publisher.publish('foo') // nothing happens

subscription.attach()
publisher.publish('foo') // stuff happens

ajax

snack.toQueryString

Converts an object of key value pairs to a URI query string.

Signature

snack.toQueryString(obj)

Arguments

  1. obj (Object) - Key value pairs

Returns

String - A URI query string

Examples

var str = snack.toQueryString({
  foo: 'bar',
  baz: 'quux'
})

str //> 'foo=bar&baz=quux'

snack.JSONP

Requests JSON data with script tag injection and handles the callback.

Signature

snack.JSONP(params, callback)

Arguments

  1. params (object)
    • url (string) - The url to request.
    • key (string) - The callback key used by the remote server.
    • data (mixed) - Object of key value pairs or a URI query string to append to the request.
    • now (boolean: optional, defaults to true) - If false, will not send request upon object creation, otherwise the request is made immediately.
  2. callback (function) - The function to call when the request is complete.

    Signature

    function (data)

    Arguments

    1. data (object) - The JSON data requested.

Returns

Object - A new JSONP object.

Examples

var params = {
  url: 'https://ajax.googleapis.com/ajax/services/search/news',
  key: 'callback',
  data: { q: 'LDS General Conference', v: '1.0', rsz: 8 }
}

snack.JSONP(params, function (data){
  console.log(data) // news!
})

Notes

JSONP (JSON with Padding) is a technique used to make a JSON request to a server (same-domain or not). It's nothing more than simply injecting a <script> tag that calls a function in your page with the sole argument being the JSON data.

The key param tells the server what function with which to pad the JSON. So if the key were jsoncallback then the script src will look something like http://example.com/?jsoncallback=someFunction, and the server will send a script file that looks something like:

someFunction({"the":"JSON Data"})

snack.JSONP handles the someFunction part for you, all you have to do is provide the right callback key that the remote server accepts.

JSONP.send

Sends the JSONP request.

Signature

JSONP.send()

Returns

Undefined

Examples

var JSONP = snack.JSONP({
  url: 'http://www.flickr.com/services/feeds/photos_public.gne',
  key: 'jsoncallback',
  data: { tags: tags, format: 'json', cacheBust: new Date().getTime() },
  now: false // won't send
}, function (data){
  // do something with data
})

JSONP.send()

JSONP.cancel

Cancels a running JSONP request.

Signature

JSONP.cancel()

Returns

Undefined

Examples

var JSONP = snack.JSONP({
  url: 'http://www.flickr.com/services/feeds/photos_public.gne',
  key: 'jsoncallback',
  data: { tags: tags, format: 'json', cacheBust: new Date().getTime() },
  now: false // won't send
}, function (data){
  // do something with data
})

$('input').attach('keyup', function (){
  JSONP.cancel()
  JSONP.send()
})

Notes

Some browsers will request the script no matter how quickly you cancel the request. However, this method is still effective at preventing the callback from being called.

snack.request

Creates a flexible, cross-browser XHR (AJAX) object.

Signature

snack.request(options, callback)

Arguments

  1. params (object)
    • url (string) - The url to request
    • data (mixed: optional) - A URI query string or object of key value pairs.
    • method (string: default get) - Accepts get, post, put, and delete.
    • now (boolean: default true) - If false, will not send request upon object creation; otherwise sends immediately.
    • headers (object: optional) - Allows setting custom headers.
    • async (boolean: default true) - If false, will send synchronous request.
    • emulation (boolean: default true) - Allows the use of put and delete methods for servers that understand it (express, rails), sent as data._method.
    • urlEncoded (boolean: default true) - Sets content-type header to www-form-urlencoded + encoding.
    • encoding (string: default 'utf-8') - Request header encoding.
  2. callback (function) - The function to call when the request is complete.

    Signature

    function (error, response)
    

    Arguments

    1. error (mixed) - The response error code, i.e. 500 or false if success.
    2. response (string) - The response text.

Returns

Object - A snack.request object.

Examples

var options = {
  method: 'post',
  url: '/items',
  data: {
    title: 'Awesome Sauce'
    body: 'This is the best sauce ever, put it on your burgers.'
  }
}

snack.request(options, function (err, res){
  // check for an error
  if (err) {
    alert('Bah! ' + err + ' error!')
    return
  }

  // no error, do what you like
  alert('Item saved')

  // handle the response data
  var item = snack.parseJSON(res)
})

request.send

Makes the XHR request. Automatically called upon object creation unless now option is false

Signature

request.send()

Returns

Object - the snack.request object.

Examples

var container = $('#container')

var req = snack.request({
  now: false, // don't send upon creation
  url: 'items/23'
}, function (err, res){
  if (err){
    alert('Crap!')
    return
  }

  container[0].innerHTML = res
})

button.attach('click', function (){
  // cancel so the container doesn't update w/ the wrong data
  req.cancel()

  // send the request
  req.send()
})

request.cancel

Cancels a running XHR request.

Signature

request.cancel()

Returns

Object - the snack.request object.

Examples

Same example as request.send

var container = snack.wrap('#container')

var req = snack.request({
  now: false, // don't send upon creation
  url: 'items/23'
}, function (err, res){
  if (err){
    alert('Crap!')
    return
  }

  container[0].innerHTML = res
})

snack.wrap('#button').attach('click', function (){
  // cancel so the container doesn't update w/ the wrong data
  req.cancel()

  // send the request
  req.send()
})