tooly
javascript utility library covering everything from dom selection and css manipulation, object inheritance and extension, logging, event handling, string formatting, etc. Basically everything that I usually want/need at my fingertips for any given project. Compatible with node, amd, and modern browsers. Just under 4kb minified and gzipped (~3kb without the
logger
andtimer
modules, which shouldn't be used in production anyway - seedist/tooly-slim.js
).
Install
$ npm install tooly
Documentation
Custom Build
You can create a custom build of particular categories.
cd path_to/node_modules/tooly
# from the tooly module root, install dev dependecies
npm install
# run the script and `include` command
# passing as arguments modules you want included
# this will also run related Grunt umd and uglify tasks
node bin/build include logger timer string
# run the `grunt build` task to wrap tooly in umd, minify etc.
grunt build
Available categories include:
collections
frankie
(jQuery-like dom selection)logger
object
string
timer
xhr
By default the custom build will be located at ./dist/tooly-custom.js
, or alternatively, you
can specify a custom output file during the build instruction:
node bin/build include dom string -o my-custom-tooly-build.js && grunt build
This should be preferred.
License
The MIT License (MIT)
© 2014 Joshua Kleckner
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Port of underscore's each. Falls back to native forEach for Arrays when available.
The iterator
argument takes the following signature for Arrays:iterator(value, index, array)
where the array is the same collection passed
as the obj
argument. For objects the signature is:iterator(value, key, object)
.
Alpha-numeric sort arrayof objects by key.
Numbers preceed letters regardless of being instances of Number
or String
.
Note that this method does modify the original array.
Example
var data = [
{name: 'a'},{name: 2},{name: 1},
{name: 'b'},{name: 'c'},{name: 'z'}
];
var ascending = tooly.sort(data, 'name');
//=> [{name: 1},{name: 2},{name: 'a'},{name: 'b'},{name: 'c'},{name: 'z'}]
// pass descending flag third arg
var descending = tooly.sort(data, 'name', true);
//=> [{name: 'z'},{name: 'c'},{name: 'b'},{name: 'a'},{name: 2},{name: 1}]
The Frankie class - named after the late, great DJ Frankie Knuckles (one of the greatest)
selectors of all time ;). A micro DOM util with a jQuery-like API.
Keeps an internal reference to a selectAll query on the passedel
. Most methods will return the instance for chainability.
append content
to all elements in the set of matched elements.
Create a new Frankie instance from all first-generation child elements of
the current set of matched elements;
TODO: try with Element.childNodes instead of children so we don't have
to do the array conversion
OR probably better to simple instantiate new Frankie
TODO: add filter
remove all child nodes from the set of matched elements.
TODO: remove listeners?
Create a new instance of Frankie with only the element
specified by index
Get the element at index i
from Frankie's selected elements.
Unlike #eq
, get
returns the actual HTMLElement.
fill each element in the set of matched elements with content
.
Replaces existing content.
If called with 1 arg, the first matched element's innerHTML is returned.
Ultra simplified wrapper for addEventListener
.
Does not currently support jQuery-style data passing
Create a Frankie instance from all parent elements of the set of matched elements.
prepend content
to all elements in the set of matched elements.
Class constructor. Simple event handling, best when inherited. Execute named functions
by triggering a Handler reference of the same name.
Example
var handler = new tooly.Handler();
function world() {
console.log('world!');
}
function hello() {
console.log('hello ');
handler.trigger('hello');
}
handler.on('hello', function() {
world();
});
hello(); //=> "hello world!";
Using #inherit, you can add all Handler functionality to your class
without having to use the handler reference:
function MyClass(name) {
// initialize the parent class
tooly.Handler.call(this);
this.name = name;
this.init();
return this;
}
// add all of the tooly.Handler.prototype methods to MyClass.prototype.
// third argument also augments MyClass.prototype
tooly.inherit(MyClass, tooly.Handler, {
init: function() {
this.on('load', function() {
console.log(this.name + ' loaded');
});
},
load: function() {
// whatever...
}
});
var instance = new MyClass("let's drink a lot of Malort and get ");
instance.load(); //=> "let's drink a lot of Malort and get loaded"
Executes all handlers attached to the named function.
For Handler#on(<name>)
to work, <name>
itself needs to call #executeHandler
.
Example
var value = 0;
var handler = new tooly.Handler();
function inc() {
value += 10;
handler.executeHandler('inc');
}
function jump() {
this.value *= 2;
}
handler.on('inc', announce);
inc();
value; //=> 20;
Add callbacks to the list of handlers. The callbacks must be an object collection of
key-value pairs where the identifier key is the name of a function that calls the#executeHandler
method with the same name as the key, while the value is the callback
function itself. This method should not be used if only registering a single callback,
for that use #on.
Remove all handler's attached to fn
. All subsequent calls to#executeHandler(fn)
will no longer have an effect.
Remove all handlers. Any subsequent call to #executeHandler
will have no effect.
Class constructor. Typical logging functionality that wraps around console.log
with css coloring and level control. The Logger level hierarchy is as follows:
- -1: off
- 0: log (no difference from console.log)
- 1: trace
- 2: debug
- 3: info
- 4: warn
- 5: error
Only calls that are greater or equal to the current Logger.level will be run.
Format
Format strings follow the same usage as node.js or the web interface, depending
on what environment you are in.
- node
- %s, %j, and %d can be used for 'string', 'json', or 'number'
- browser
- %s or %o can be used in place of 'string' or 'object'
Example
var logger = new tooly.Logger('TEST_LOGGER', { level: 2 });
logger.trace(logger); // will not output
Options
level
: number (default 2: debug)bypassTimestamp
: boolean (default: false)bypassLine
: boolean (remove line number from output prefix. default: false)textFormat
: a css for a%c
flag, ie.'color:blue;font-size:22px;'
lineFormat
: same as textFormat for line number styling
All active loggers in the current context can be disabled, regardless of level,
by setting the static tooly.Logger.off = true
. Setting back to false will resume
logging at each loggers previous level.
Add the "own properties" of src
to dest
.
Used throughout the application to add prototype
methods to tooly classes without
assigning Object as their prototype.
Object literal assignment results in creating an an object with Object.prototype
as the prototype. This allows us to assign a different prototype while keeping
the convenience of literal declaration.
Helper to perform prototypal inheritance.
Note that this method overwrites the child's original prototype.
Also note that the child's constructor needs to call parent.call(this)
Extensively check if obj
is "falsy".
isFalsy returns true for the following:
var undefinedValue;
var nullValue = null;
var setUndefined = undefined;
var falseValue = false;
var zero = 0;
var emptyString = ''; // same for ' \n\t \n'
var falseString = 'false';
var zeroString = '0';
var nullString = 'null';
var undefinedString = 'undefined';
Note that in the cases of falsy strings, the check is
done after a call to String.trim
, so surrounding
whitespace is ignored:isFalsy('\n\t false \n') //=> true
A more useful alternative to the typeof operator.
If only the obj
argument is passed, the class of that object is returned.
If the second argument klass
is passed, a boolean indicating whether obj
is of class klass
or not is returned.
minimal Function version of ECMAScript6 String.prototype.contains
.
minimal Function version of ECMAScript6 String.prototype.endsWith
.
get the extension of a file, url, or anything after the last .
in a string.
Utility method to convert milliseconds into human readable time
Extracts final relative part of url, optionally keeping forward,
backward, or both slashes. By default both front and trailing slashes are removed
minimal Function version of ECMAScript6 String.prototype.startsWith
.
Get a copy of str
without file extension, or anything after the last .
(does not change the original string)
Simple DOM element creation using jade-like syntax for the element
declaration and options hash for attributes. The attribute hash can take a content
argument for the element's innerHTML property, which itself can be another tag
Examples
tag('a'); //=> <a></a>
tag('a.link--plain') //=> <a class="link--plain"></a>
tag('a', 'MUSIC!!!') //=> <a>MUSIC!!!</a>
tag('a#main.link--plain', { rel: 'nofollow', href: 'music', content: 'MUSIC!!!' })
//=> <a href="music" rel="nofollow">MUSIC!!!</a>
tag('#main', tag('.sub')) //=> <div id="main"><div class="sub"></div></div>