Skip to content

dammynex/zap-js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 

Repository files navigation

zap-js

Tiny client-side router for javascript.

Routing

It's quite basic

Add zap to <body>

  <script src="/path/to/zap.js"></script>

Adding routes

Static routes

var $router = new Zap()

$router.on('/', function (params) {

    console.log('We are home')
})

$router.on('/book/45' function (params) {

    console.log('I want to read book 45')
})

Dynamic routes

var $router = new Zap()

$router.on('/book/:id' function (id, params) {

    console.log('I want to read book with id ', id)
})

$router.on('/book/:id/:author', function (id, author, params) {

    console.log('I want to read a book which id is ' + id + ' and author is ' + author)
})

Routing with query strings

You can as well get the value of query strings from routes

eg. We have a url like

http://example.com/book/?id=45&author=dammy

We can write our route like

$router.on('/book', function (params) {

    console.log('I want to read a book which id is ' + params.id + ' and author is' + params.author)
})

Let the router listen to routes

After you have added all routes, you'll have to trigger router to listen to routes

$router.$trigger()

Go to route

//$router.$go(path)
$router.$go('/book/45')

Force all <a> elements to follow route using jquery

$( function () {
  $('a').on('click', function (e) {
     $router.$go( $(this).attr('href') )
     e.preventDefault()
  })
})

Or just add data-zap attribute to <a> elements to make them follow routes

<a href="/book/45" data-zap>
  Read book 45
</a>

La fin!

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published