A simple, lightweight library making it easy to create routes or run events based on a specific URL hashtag.
Switch branches/tags
Nothing to show
Pull request Compare This branch is 144 commits behind baseprime:master.
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
examples
js
.gitignore
LICENSE.txt
README.md

README.md

Grapnel.js

A lightweight JavaScript library making it easy to run events based on a specific URL hashtag.

An example:

Basic usage

var hook = new Grapnel(':');

hook.add('show', function(value){
    console.log('Showing: %s', this.value);
});

The URL

http://mysite.com/products#show:widgets

Would log in console

Showing: widgets

RegEx

var expression = /are/g;
var hook = new Grapnel(expression);

hook.add('tacos', function(value){
    console.log('Someone thinks %s are %s.', this.action, this.value);
});

The URL

http://domain.com/page#tacosaregood

Would log in console

Someone thinks tacos are good.

Simple JavaScript Router using jQuery

<!DOCTYPE html>
<html>
<head>
<title>This is a static page</title>
<script type="text/javascript" src="/path/to/Grapnel.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
var router = new Grapnel('/');

router.add('products', function(){
    var page = this.value + '.html';
    // GET widgets.html
    $('body').load(page);
});
</script>
</head>
<body>
<h1>This is a static page</h1>
<p><a href="#products/widgets">Click Here to view my widgets</a></p>
</body>
</html>

 


Documentation

Instantiation

Initializing Grapnel.js is easy. To create an instance:

// First argument can be a String or RegEx (Default: ":")
var hook = new Grapnel();

Methods

add Adds a new action listener
/**
 * @param {String} action
 * @param {Function} callback
*/
hook.add('find', function(){
    // this.value, this.action, this.hook
    // this.matches();
    // this.setAnchor('something');
    // this.clearAnchor();
    console.log('Finding %s', this.value);
});
on Adds a new event listener
/**
 * @param {String|Array} event
 * @param {Function} callback
*/
hook.on('match', function(value, action){
    console.log('Grapnel.js works! (Hook: "%s", Action: "%s", Value: "%s")', this.hook, action, value);
});
matches Return array of matching actions
setAnchor Sets a new absolute anchor
getAnchor Get absolute anchor
clearAnchor Clears the anchor (replaces URL with #! appended to it)

Events

match A matched hook is found
hashchange Anchor hashtag is changed

License

MIT License

Todo

Add support for older browsers not supporting window.onhashchange (IE lte 7.0)

Changelog

0.1.1
  • Compatibility: Map Array workaround for compatibility issues with archaic browsers
  • Added this.version property
0.1.0
  • Initial release