DailyJS

DailyJS

The JavaScript blog.


Tagtime
Featured

jquery plugins forms calendars time widgets

jQuery Roundup: persistState, CLNDR.js

Posted on .

Note: You can send your plugins and articles in for review through our contact form or @dailyjs.

persistState

persistState (GitHub: togakangaroo / persistState, License: MIT) by George Mauer saves the state of UI widgets. It can be applied to a selector, so you can save the state of a specific set of widgets rather than all of them.

I like the idea of using this to save the state of form controls, particularly in a multi-stage form that's handled client-side. Values are saved to localStorage, and the API of persistState allows you to swap in your own serialisation handler.

Saving the state of form controls looks like this:

$.ow.persistState.elementPersistence['textarea,input:not(:checkbox),select'] = {
  saveState: function($el) {
    return { val: $el.val() };
  },

  restoreState: function($el, state) {
    if (!state) return;
    if ($el.val() !== state.val)
      $el.val(state.val).trigger('change');
  }
};

CLNDR.js

CLNDR.js (GitHub: kylestetz / CLNDR, License: MIT) by Kyle Stetz is a calendar plugin:

There are wonderful and feature-rich calendar modules out there and they all suffer the same problem: they give you markup (and often a good heap of JS) that you have to work with and style. This leads to a lot of hacking, pushing, pulling, and annoying why-can't-it-do-what-I-want scenarios.

CLNDR doesn't generate markup (well, it has some reasonable defaults, but that's an aside). Instead, CLNDR asks you to create a template and in return it supplies your template with a great set of objects that will get you up and running in a few lines.

CLNDR requires Moment.js, which is OK because I don't leave home without it!

Featured

jquery date plugins time text state-machine

jQuery Roundup: Orangevolt Ampere, Succinct, jQuery Age

Posted on .

Note: You can send your plugins and articles in for review through our contact form.

Orangevolt Ampere

Orangevolt Ampere

If you like state machines, then you might find Orangevolt Ampere (GitHub: lgersman / jquery.orangevolt-ampere, License: MIT/GPL2) interesting. Created by Lars Gersmann, it uses AngularJS, jQuery, Boostrap, and Font Awesome and attempts to help you model single page applications by encapsulating data operations and route transitions in state machines. That means your applications get some features for "free", like infinite undo/redo.

The author has made a presentation about Orangevolt Ampere that gently introduces the main concepts, which I recommend looking at before diving into the code.

The wizard example is a good example of how state machines can model something that would ordinarily be awkward to work with.

Succinct

Succinct (GitHub: micjamking / succinct, License: MIT) by Mike King is a text truncation plugin. It truncates based on the simplest case where you know the number of characters you want to display: $('.truncate').succinct({ size: 80 }) will cut text down to 80 characters and add an ellipsis.

jQuery Age

jQuery Age (GitHub: ksylvest / jquery-age) by Kevin Sylvestre formats and tracks dates and times as human readable text. It allows the text suffixes and grammatical formatting to be overridden, so it could be internationalised as needed.

<time datetime="2010-01-01T12:00:00Z" class="age">January 1, 2010 12:00</time>  
<time datetime="2020-01-01T12:00:00Z" class="age">January 1, 2020 12:00</time>

<script type="text/javascript">  
  $('.age').age();
</script>  

Featured

testing node modules time async promises unix daemons

Node Roundup: wish, Vow, shell-jobs

Posted on .

You can send in your Node projects for review through our contact form.

wish

wish (GitHub: EvanBurchard / wish, License: MIT, npm: wish) by Evan Burchard is an assertion module designed to raise meaningful, human-readable errors. When assertions fail, it parses the original source to generate a useful error message, which means the standard comparison operators can be used.

For example, if wish(a === 5) failed an error like this would be displayed:

WishError:  
  Expected "a" to be equal(===) to "5".

If assert(a === 5) had been used instead, AssertionError: false == true would have been raised. A fairer comparison would be assert.equal, which would produce AssertionError: 4 == 5, but it's interesting that wish is able to introspect the variable name and add that to the error.

Vow

Vow (GitHub: dfilatov / jspromise, License: MIT/GPL, npm: vow) by Filatov Dmitry is a Promises/A+ implementation. Promises can be created, fulfilled, and rejected -- you should be able to get the hang of it if you've used libraries with then methods elsewhere, but there are some differences to Promises/A which feels like it actually simplifies some of the potentially messier parts of the original CommonJS specification.

Here's an example of the Vow API:

var promise1 = Vow.promise(),  
    promise2 = Vow.promise();

Vow.all([promise1, promise2, 3])  
  .then(function(value) {
    // value is [1, 2, 3]
  });

promise1.fulfill(1);  
promise2.fulfill(2);  

The author has written some pretty solid looking tests, and benchmarks are included as well. The project performs favorably when compared to other popular promise libraries:

 mean timeops/sec
Q54.891ms18
When3.484ms287
Vow1.158ms864

shell-jobs

I like seeing daemons made in Node, and Azer Koçulu recently sent in a cron-inspired daemon called shell-jobs (GitHub: azer / shell-jobs, License: MIT, npm: shell-jobs). It uses .jobs files that are intended to be human readable. All you need to do is write a shell command followed by a # => and then a time:

cowsay "Hello" > /tmp/jobs.log # => 2 minutes  

The shell-jobs script will then parse this file and output the following:

  jobs Starting "cowsay "Hello" > /tmp/jobs.log" [2 minutes] +2ms

After two minutes has passed the job will be executed:

  exec 1. Running cowsay "Hello" > /tmp/jobs.log. +0ms

Featured

frameworks libraries date history node modules time keyboard ender responsive

Ender Roundup: tablesort.js, Moment.js, jwerty, SelectNav.js, ender-events, ender-assert, Categorizr.js, Arbiter

Posted on .

You can send in your Ender-related projects for review through our contact form or @dailyjs. Be sure to also update the Ender package list page on the Ender wiki.

tablesort.js

tablesort.js (GitHub: tristen/tablesort, npm / Ender: tablesort) by Tristen Brown is a dependency-free sorting library for HTML tables. tablesort.js can be invoked stand-alone via new Tablesort(document.getElementById('table-id')) or $('#table-id').tablesort() method from within Ender.

Olivier Vaillancourt has written a small review of tablesort.js for use in Ender on Twitter Bootstrap tables.

Moment.js

Moment.js (GitHub: timrwood/moment, npm / Ender: moment) by Tim Wood is small, yet very comprehensive date and time handling library.

Moment.js

Moment.js was mentioned last year on DailyJS but it now has a simple Ender bridge allowing you to pack it neatly into Ender builds for use via $.ender(). Plus, it's an absolutely fantastic library for anything date/time related so it's worth mentioning again. Be sure to scan the docs to see just how much this library can do.

$.moment().add('hours', 1).fromNow(); // "1 hour ago"

// manipulate
$.moment().add('days', 7).subtract('months', 1).year(2009).hours(0).minutes(0).seconds(0);

// parse dates in different formats
var day = $.moment("12-25-1995", "MM-DD-YYYY");

var a = $.moment([2010, 1, 14, 15, 25, 50, 125]);  
a.format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Sunday, February 14th 2010, 3:25:50 pm"  
a.format("ddd, hA"); // "Sun, 3PM"

// operate on different 'moment' objects
var a = $.moment([2007, 0]);  
var b = $.moment([2008, 5]);  
a.diff(b, 'years'); // 1  
a.diff(b, 'years', true); // 1.5  

The project maintainers also follow a rigorous release methodology, making great use of git branches, something that is not often found on smaller open source libraries.

jwerty

jwerty (GitHub: keithamus/jwerty, Licence: MIT, npm / Ender: jwerty) by Keith Cirkel is a small keyboard event handling library which can bind, fire and assert key combination strings against elements and events.

$.key('ctrl+shift+P', function () { [...] });
$.key('⌃+⇧+P', function () { [...] });

// specify optional keys
$.key('⌃+⇧+P/⌘+⇧+P', function () { [...] });

// key sequences
$.key('↑,↑,↓,↓,←,→,←,→,B,A,↩', function () { [...] });

// pass in a selector to bind a shortcut local to that element
$.key('⌃+⇧+P/⌘+⇧+P', function () { [...] }, 'input.email', '#myForm');

// use `$.event` as a decorator, to bind events your own way
$('#myinput').bind('keydown', $.keyEvent('⌃+⇧+P/⌘+⇧+P', function () { [...] }));

// use `$.isKey` to check a key combo against a keyboard event
function (event) {  
    if ( $.isKey('⌃+⇧+P', event) ) { [...] }
}

// use `$.fireKey` to send keyboard events to other places
$.fireKey('enter', 'input:first-child', '#myForm');

SelectNav.js

SelectNav.js (GitHub: lukaszfiszer/selectnav.js, npm / Ender: selectnav.js) by Lukasz Fiszer is a small library that will convert your website's navigation into a <select> menu. Used together with media queries it helps you to create a space saving, responsive navigation for small screen devices. SelectNav.js is inspired by TinyNav.js for jQuery.

ender-events and ender-assert

ender-events (GitHub: amccollum/ender-events, Licence: MIT, npm / Ender: ender-events) and ender-assert (GitHub: amccollum/ender-assert, Licence: MIT, npm / Ender: ender-assert) are two packages by Andrew McCollum, previously bundled in his node-compat library. ender-events gives you an implementation of the NodeJS EventEmitter class in your browser, while ender-assert gives you a browser version of the NodeJS assert module.

Andrew also has a tiny extension to Bonzo, the DOM utility included in Ender's starter pack (The Jeesh), named ender-remove that simply triggers a 'remove' event when nodes are removed from the DOM. Which can be helpful for performing clean-up actions.

Categorizr.js

Categorizr.js (GitHub: Skookum/categorizr.js, Licence: MIT, npm / Ender: categorizr) by Dustan Kasten is a JavaScript port of the Categorizr PHP script by Brett Jankord.

Categorizr gives you $.isDesktop() $.isTablet() $.isTV() $.isMobile() methods to determine the current device.

Arbiter

Arbiter (GitHub: iamdustan/arbiter, Licence: MIT, npm / Ender: arbiter) also by Dustan Kasten is a tiny library for managing the HTML5 history interface via pushState(), using AJAX requests to load new content upon request.

Featured

libraries date screencasts time maths backbone.js

Backbone.js Screencasts, XDate, JavaScript BigInteger Library

Posted on .

Backbone.js Screencasts

Backbone.js Screencasts is a commercial set of
Backbone.js tutorials from 30 Cubits that costs \$9 (until November 9th, then \$18 thereafter) for 106 minutes of videos. The videos cover the
core Backbone.js functionality like views, routers, events, models,
collections, and also how to use other JavaScript techniques alongside
your Backbone.js code.

There's a preview of the content on Vimeo here: Backbone.js Quickly -
Preview
.

XDate

XDate (GitHub: arshaw / xdate, License: dual MIT and GPL)
by Adam Shaw is a wrapper around Date that provides
improved date parsing, formatting, and manipulation. XDate format
strings
really help with
formatting dates, which I find myself doing a lot lately in Node or
single page applications.

Here's an example of XDate's formatting method:

new XDate(2011, 0, 1, 6, 0).toString('d/M/yy h(:mm)TT');

Another useful feature of this library is the set of XDate diffing
methods
. They provide a friendly API
around date subtraction.

Most of XDate's methods return an XDate, so it's chainable
too:

d1 = new XDate();
d2 = d1.clone()
       .setUTCMode(true)
       .setDate(1)
       .addMonths(1)
       .addYears(2);

JavaScript BigInteger Library

The JavaScript BigInteger Library
(GitHub: silentmatt / javascript-biginteger,
License: MIT) by Matthew Crumley is a BigInteger library for
JavaScript. The author has written detailed blog posts on how the
library works and the algorithms behind it:

If you look at the source, you'll probably notice that I'm actually using base 10000000, not base 10. I'm using decimal in these examples because it makes things clearer but everything works pretty much exactly the same way in any base. Using a larger base just makes things more efficient because you get 7 digits in each array entry.

Matthew created this library to support his Google Chrome Scientific
Calculator
.