Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support filtering DOM nodes that will be processed in href() #26

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,23 @@ href(function (href) {
})
```

Often it is useful to filter the urls that the `href()` callback will be called with. You can do this by providing a second parameter containing a filtering function.

For example, if we wanted to filter out all link clicks that have been tagged with a data attribute `data-external-link` we could do it like this:

```js
const href = require('sheet-router/href')
href(function (url) {
router(url)
console.log('link was clicked: ' + url)
}, allowInternalLinks)

function allowInternalLinks(node) {
const isExternalLink = node.hasAttribute('data-external-link')
return !isExternalLink
}
```

### virtual-dom example
```js
const render = require('virtual-dom/create-element')
Expand Down Expand Up @@ -141,7 +158,7 @@ that are then passed to the matched routes. Cleans urls to only match the
### history(cb(href))
Call a callback to handle html5 pushsState history.

### href(cb(href))
### href(cb(href), filterFn(domNode)?)
Call a callback to handle `<a href="#">` clicks.

## See Also
Expand Down
6 changes: 4 additions & 2 deletions href.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ module.exports = href
// handle a click if is anchor tag with an href
// and url lives on the same domain. Replaces
// trailing '#' so empty links work as expected.
// fn(str) -> null
function href (cb) {
// fn(str) -> fn(node)? -> null
function href (cb, filterFn) {
assert.equal(typeof cb, 'function', 'cb must be a function')

window.onclick = function (e) {
Expand All @@ -21,6 +21,8 @@ function href (cb) {

if (!node) return

if (filterFn && !filterFn(node)) return

e.preventDefault()
const href = node.href.replace(/#$/, '')
cb(href)
Expand Down