Docs

Everything You Need to Know

Utilities

Use

ChocolateChip-UI provides a number of utility functions for you to use. The first set are as follows:

  • $.noop()
  • $.uuid()
  • $.require()
  • $.delay()
  • $.each()
  • $.replace()
  • $.isEmptyObject()
  • $.isInteger()
  • $.isFloat()
  • $.type()
  • $.encode()
  • $.escapeHTML()
  • $.concat()
  • $.mixin()
  • $.unique()
  • $.compare()
  • $.paginate()
  • $.flatten()
  • $.throttle()
  • $.debounce()
  • $.once()
  • $.before()
  • $.after()

ChocolateChip-UI also provides the following array utilities:

  • Array.pluck(property)
  • array1.difference(array2)
  • array1.intersection(array2)
  • array1.mixin(array2)
  • array.unique()

$.noop()

$.noop() is a filler function for when you need to pass a callback, but don't want anything to happen. It stands for no operation performed. You can use it like this:

$('button').on('tap', $.noop);

$.uuid()

$.uuid() create a uuid. This is a string. You can use it to create a unique identifier for objects in a collection, or for ids of DOM elements. ChocolateChip-UI uses $.uuid internally for this purpose.

$.require()

$.require(scriptUrl) is used to import a script into your document. It takes upto three arguments:

  • A url for the script you wish to import
  • A callback to execute when the script is fully loaded
  • A context to use within the callback

This takes the url that you provide and creates a script tag. It appends the script tag to the document's head. This causes the browser to attempt to load the script. If the script loads successfully, the provided callback will be executed. If a context, such as a DOM node, was provided as well, this will be passed to the callback as its first argument.

$.require('/js/I-need-this-now.js', function(results) {
  // Run function imported from required script:
  var stuff = getStuffFromRequiredScript();
  // Output stuff into the provided context:
  results.html(stuff)
}, $('#results'))

$.delay()

$.delay(milliseconds) allows you to execute a callback with a delay. It is like setTime, except that this returns a promise and you pass your callback to a then function:

// Delay execute by 2 seconds:
$.delay(2000)
  .then(function() {
    // Do whatever you want to here...
  });

$.each()

$.each(object/array, callback) allows you to iterate over an object of key/values or over an array. When the first argument is an object, the callback's parameters will be: key, value. When the first argumnet is an aray, the callback's parameters are: index, context. This works like the jQuery equivalent.

// An object:
var person = {
  firstName: 'Joe',
  lastName: 'Bodoni',
  job: 'Developer',
  employer: 'Twitter'
}
$.each(person, function(key, value) {
  console.log(`${object[key]} is ${value}`);
});

// An array:
var fruits = [
  'apples',
  'oranges',
  'bananas',
  'strawberries',
  'peaches',
  'cherries'
];
$.each(fruits, function(idx, ctx) {
  // only print out first 5:
  if (idx > 4) return;
  var number = idx + 1;
  console.log(`${number}: ${ctx}`);
});

$.replace()

$.replace(newElement, oldElement) allows you to replace one element with another. The new element is the first argument. This might be a string of markup, or a DOM node or a ChocolateChip-UI DOM reference. If the element you are using to replace already exists in the document, it will be plucked from its current location and inserted in the place where the target element was. Otherwise, if it is a new element, the old element will simply be replaced.

// Replace the title element with a new one:
var currentTitle = $('h1');
var newTitle = `<h2>New Title</h2>`;
$.replace(newTitle, currentTitle)

jQuery has replaceWith(), but it works quite differently from this. We feel ChocolateChip-UI's replace is more straightforward about what it's doing than jQuery's replaceWith. ChocolateChip-UI's replace works even when jQuery is present because it is included as a utlity plugin.

$.isEmptyObject()

$.isEmptyObject(object) tests where an object is {} or where it has properties. This is a boolean value.

$.isInteger()

$.isInteger(number) tests whether the number is an integer or not. This is a boolean value.

$.isFloat()

$.isFloat(number) tests whether the number is a float or not. This is a boolean value.

$.type()

$.type(argument) lets you find out what type the argument is. It can test for boolean, number, string, function, array, date, error, regexp, object.

if ($.type(data) === 'array') {
  data.forEach(function(item, index) {
    console.log(item)
  });
}

$.encode()

$.encode(data) returns the value from a form element encoded.

$.escapeHTML()

$.escapeHTML(data) escapes the html tags, parenthesis, etc.

$.concat()

$.concat(args) takes a series of strings and returns one string. This is useful where you need to concatenate a lot of string pieces together, but don't want to have to use + for concatenation:

var str = $.concat('This', ' ', 'is', ' ', 'a' , ' ', 'string', '.');
// returns: 'This is a string.'

$.mixin()

$.mixin(sourceObject, targetObject) allows you to "mixin" one object into another. If a property already exists on the target object, its property will not be replaced nor will its value be changed. Mixing in a object into another only adds properties from the one object to the target.

// Mixin two objects:
var myObj = {
  name: 'Sam',
  age: 32,
  address: '1234 Main Street'
};
var newObj = {
  job: 'Brain Surgeon',
  salary: '200000',
  age: 99,
  address: 'unknown'
};
$.mixin(newObj, myObj);
console.dir(myObj);
/*
{
  name: 'Sam',
  age: 32,
  address: '1234 Main Street',
  job: 'Brain Surgeon',
  salary: '200000'
}
*/

Notice in the above example that because age and address already existed on myObj that they were not affected by the mixin values. Only new properties were added from newObj to myObj.

$.unique()

$.unique() takes an array as its argument. It returns a new array free of duplicates.

var people = [
  {firstName: 'Anne', lastName: 'Kimble'},
  {firstName: 'Anne', lastName: 'Kimble'},
  {firstName: 'Anne', lastName: 'Kimble'},
  {firstName: 'Anne', lastName: 'Kimble'},
  {firstName: 'Howard', lastName: 'Nelson'},
  {firstName: 'Howard', lastName: 'Nelson'},
  {firstName: 'Joe', lastName: 'Bodoni'},
  {firstName: 'Joe', lastName: 'Bodoni'},
  {firstName: 'Joe', lastName: 'Bodoni'},
  {firstName: 'Joe', lastName: 'Bodoni'},
  {firstName: 'Sam', lastName: 'Daniels'},
  {firstName: 'Sam', lastName: 'Daniels'},
  {firstName: 'Tom', lastName: 'Johnson'},
  {firstName: 'Tom', lastName: 'Johnson'},
  {firstName: 'Tom', lastName: 'Johnson'}
];
var actualPeople = $.unique(people);
/* result:
[
  {firstName: 'Anne', lastName: 'Kimble'},
  {firstName: 'Howard', lastName: 'Nelson'},
  {firstName: 'Joe', lastName: 'Bodoni'},
  {firstName: 'Sam', lastName: 'Daniels'},
  {firstName: 'Tom', lastName: 'Johnson'}
]
*/

$.compare()

$.compare(argument1, argument2) allows you to compare two things and get a boolean response. The items to compare may be simple values, such as strings or numbers, or objects or arrays. For objects and arrays, they must be identical for a match. If the two items match, this returns true, otherwise false.

// Compare numbers:
$.compare(1, 1) // returns true
$.compare(1, 2) // returns false

// Compare strings:
var str1 = 'one';
var str2 = 'two';
var str3 = 'one';
$.compare(str1, str2) // returns false
$.compare(str1, str2) // returns true

// Compare objects:
var obj1 = {
  value: 1
}
var obj2 = {
  value: 'whatever'
}
var obj3 = {
  value: 1
}
$.compare(obj1, obj2) // returns false
$.compare(obj1, obj3) // returns true

// Compare arrays:
var array1 = [1,2,3];
var array2 = [4,5,6];
$.compare(array1, [1,2,3]) // returns true
$.compare(array1, array2) // returns false
$.compare([4,5,6], array2) // returns true
          

$.paginate()

$.paginate(data, itemsPerPage) allows you to get back chuncks of an array in a specified size. This is useful where you have a large array items and you want to show it in chunks, such as with the paging widget. It takes the array of data, and the number of items each page should hold. If an array had 100 items, you could break it down into five pages of 20 items each as follows:

// Break array of 100 items into 
// 5 arrays of 20 items each:
var paginatedData = $.paginate(arrayOf100Items, 20);
// paginatedData is an array of five arrays with 20 items each.
paginatedData.length // 5
paginatedData[0].length // 20
paginatedData[1].length // 20
paginatedData[2].length // 20
paginatedData[3].length // 20
paginatedData[4].length // 20

$.flatten(array)

This method takes and array of nested array and returns it flattened. The original array is left untouched. You use it like this:

// Flatten a nested array:
var nestedArray = [[[1], [2], 3, [[4, 5], 6], 7], 8];
var flattenedArray = $.flatten(nestedArray);
// returns [1,2,3,4,5,6,7,8]

$.throttle()

$.throttle() allows you to control how often a set of events fire. If you are listening for keystokes in an input, you can capture the event a designated amount of time. This helps you avoid a flood of events. This method takes two arguments, a callback to execute and the time in milliseconds to wait before the next execution.

$('input').on('input', $.throttle(function(e) {
  // If only a few letters, exit:
  if (this.value.length < 2) return;

  // Output current value of input:
  console.log(this.value);
}, 1000);

You can pass $.throttle a third argument to control when it fires. This third argument is an object of options. By default, $.throttle fires on the leading-edge. You can disable this by passing the object {leading: false}:

$('input').on('input', $.throttle(function(e) {
  // do something here
}, 1000, {leading: false});

By default $.throttle also fires on the trailing-edge. You can disable this by passing the object {trailing: false} as the last argument:

$('input').on('input', $.throttle(function(e) {
  // do something here
}, 1000, {trailing: false});

And of course you can combine both options together:

$('input').on('input', $.throttle(function(e) {
  // do something here
}, 1000, {leading: false, trailing: false});

$.debounce() differs from $.throttle() in that it waits the designated time before firing the event. Given a stream of events, only the last will be executed.

Debounce takes two arguments: a callback and the amount of time in milliseconds before firing.

$.debounce()

$('input').on('input', $.debounce(function(e) {
  // do something here
}, 1000);

In the above example, regardless of how many keystrokes are executed, the callback won't fire until one second after the user stops typing. By default $.debounce fires on the trailing-edge of the wait period. You can force it to fire on the leading-edge by passing a truthy third argument. You might want to do this to avoid an accidental double tap on a submit button:

$('input').on('input', $.debounce(function(e) {
  // do something here
}, 1000, true);

$.once()

There may be times where you only want a function to execute once, no matter how many times the user tries to run it. A submit button is a good example. Using $.once() you can do this. You pass it the function you want to execute, and it returns wrapped so that it will only execute once:

// Execute function only once:
var alertUser = function(message) {
  alert(message)
};
var newAlert = alertUser('A message from your sponsors!');
$('#alertButton').on('tap', $.once(newAlert);

In the above code, the callback will only execute one time, even if the user taps more times.

NOTICE:

You should not define your callback nor pass it any arguments inside the $.once method. Doing so will cause the callback to be executed as soon as the page loads. Instead take care to define your callback separately and pass it as a simple argument to $.once as done in the example above.

The following code will fail to work properly because we are passing an argument to the callback inside the $.once method:

// Execute function only once:
var alertUser = function(message) {
  alert(message)
};
$('#alertButton').on('tap', $.once(alertUser('A message from your sponsors!'));

$.before(times, callback)

This function takes the number of times and wraps the callback so that it will only execute x times before the times argument is reached. For example, if you pass a times of 4, the callback will execute only the first 3 times. After that it will not execute. Use this method to limit a callback to only execute a specific number of times.

// Execute the callback only 3 times:
var alertUser = function(message) {
  alert(message)
};
var newAlert = alertUser('A message from your sponsors!');
// Pass 4 so that the callback only executes 3 times:
$('#alertButton').on('tap', $.before(4, newAlert);
NOTICE:

You should not define your callback nor pass it any arguments inside the $.before method. Doing so will cause the callback to be executed as soon as the page loads. Instead take care to define your callback separately and pass it as a simple argument to $.before as done in the example above.

The following code will fail to work properly because we are passing an argument to the callback inside the $.before method:

// Execute the callback only 3 times:
var alertUser = function(message) {
  alert(message)
};
$('#alertButton').on('tap', $.before(4, alertUser('A message from your sponsors!'));

$.after(times, callback)

This function takes the number of times and wraps the callback so that it will only execute on the times attempt. For example, if you pass a times of 4, the callback will not execute until after the fourth attempt. After that the callback will execute on every attempt. Use this method to prevent a callback from being executed until after the specified number of attempts.

// Execute the callback only on and after 3 attempts:
var alertUser = function(message) {
  alert(message)
};
// Pass 3 so that the callback only executes on and after the third attempt:
var newAlert = alertUser('A message from your sponsors!');
$('#alertButton').on('tap', $.after(3, newAlert);
NOTICE:

You should not define your callback nor pass it any arguments inside the $.after method. Doing so will cause the callback to be executed as soon as the page loads. Instead take care to define your callback separately and pass it as a simple argument to $.after as done in the example above.

The following code will fail to work properly because we are passing an argument to the callback inside the $.after method:

// Execute the callback only on and after 3 attempts:
var alertUser = function(message) {
  alert(message)
};
$('#alertButton').on('tap', $.after(3, alertUser('A message from your sponsors!'));

ChocolateChip-UI provides two functions to enable and dispable form elements:

  • $(input).enable()
  • $(input).disable()

Array Extras

ChocolateChip-UI provides the following array extras. These are polyfills and will not overwrite any existing array methods.

Array.pluck(property)

This method allows you to pluck all objects in the array with that property. It returns a new array of just those property values.

// Pluck first names:
var people = [
  {firstName: 'Anne', lastName: 'Kimble'},
  {firstName: 'Howard', lastName: 'Nelson'},
  {firstName: 'Joe', lastName: 'Bodoni'},
  {firstName: 'Sam', lastName: 'Daniels'},
  {firstName: 'Tom', lastName: 'Johnson'}
];
var firstNames = people.pluck('firstName');
// firstNames is: ['Anne', 'Howard', 'Joe', 'Sam', 'Tom']
          

array1.difference(array2)

This method allows you to compare one array against another. It returns all objects in the first array that are not in the second.

// Find difference:
var people1 = [
  {firstName: 'Sam', lastName: 'Daniels'},
  {firstName: 'Howard', lastName: 'Nelson'},
  {firstName: 'Joe', lastName: 'Bodoni'}
];
var people2 = [
  {firstName: 'Sam', lastName: 'Daniels'},
  {firstName: 'Joe', lastName: 'Bodoni'}
];
var difference = people1.difference(people2);
// difference is [{firstName: 'Howard', lastName: 'Nelson'}]
          

array1.intersection(array2)

This method lets you find all objects or values shared between two arrays.

// Find the intersection:
var people1 = [
  {firstName: 'Sam', lastName: 'Daniels'},
  {firstName: 'Howard', lastName: 'Nelson'},
  {firstName: 'Joe', lastName: 'Bodoni'},
  {firstName: 'Anne', lastName: 'Kimble'}
];
var people2 = [
  {firstName: 'Sam', lastName: 'Daniels'},
  {firstName: 'Tom', lastName: 'Johnson'},
  {firstName: 'Joe', lastName: 'Bodoni'}
];
var shared = people1.difference(people2);
/* shared is: [
  {firstName: 'Sam', lastName: 'Daniels'},
  {firstName: 'Joe', lastName: 'Bodoni'}
] */
          

array1.mixin(array2)

This method lets you mixin the objects of one array to another. If the objects already exist in the target, they will not be added.

// Mixin in array:
var people1 = [
  {firstName: 'Sam', lastName: 'Daniels'},
  {firstName: 'Howard', lastName: 'Nelson'},
  {firstName: 'Joe', lastName: 'Bodoni'},
  {firstName: 'Anne', lastName: 'Kimble'}
];
var people2 = [
  {firstName: 'Sam', lastName: 'Daniels'},
  {firstName: 'Tom', lastName: 'Johnson'},
  {firstName: 'Joe', lastName: 'Bodoni'}
];
people1.mixin(people2);
/* result:
[
  {firstName: 'Sam', lastName: 'Daniels'},
  {firstName: 'Howard', lastName: 'Nelson'},
  {firstName: 'Joe', lastName: 'Bodoni'},
  {firstName: 'Anne', lastName: 'Kimble'},
  {firstName: 'Tom', lastName: 'Johnson'}
]
*/
          

array.unique()

This method lets you remove any duplicates from an array. This works with arrays of simple values as well as with objects.

// Remove duplicates:
var people = [
  {firstName: 'Anne', lastName: 'Kimble'},
  {firstName: 'Anne', lastName: 'Kimble'},
  {firstName: 'Anne', lastName: 'Kimble'},
  {firstName: 'Anne', lastName: 'Kimble'},
  {firstName: 'Howard', lastName: 'Nelson'},
  {firstName: 'Howard', lastName: 'Nelson'},
  {firstName: 'Joe', lastName: 'Bodoni'},
  {firstName: 'Joe', lastName: 'Bodoni'},
  {firstName: 'Joe', lastName: 'Bodoni'},
  {firstName: 'Joe', lastName: 'Bodoni'},
  {firstName: 'Sam', lastName: 'Daniels'},
  {firstName: 'Sam', lastName: 'Daniels'},
  {firstName: 'Tom', lastName: 'Johnson'},
  {firstName: 'Tom', lastName: 'Johnson'},
  {firstName: 'Tom', lastName: 'Johnson'}
];
people.unique();
/* result:
[
  {firstName: 'Anne', lastName: 'Kimble'},
  {firstName: 'Howard', lastName: 'Nelson'},
  {firstName: 'Joe', lastName: 'Bodoni'},
  {firstName: 'Sam', lastName: 'Daniels'},
  {firstName: 'Tom', lastName: 'Johnson'}
]
*/