Skip to content
Browse files

moveTo now dispatches a notfound event if given an invalid locus.

This is handy in a number of places, including search functionality.
  • Loading branch information...
1 parent a07cea7 commit c50bbf417cd1b7169725d28aa59673ba24b3743e @joseph joseph committed Dec 2, 2011
Showing with 21 additions and 9 deletions.
  1. +12 −2 src/core/book.js
  2. +9 −7 src/core/reader.js
View
14 src/core/book.js
@@ -49,8 +49,8 @@ Monocle.Book = function (dataSource) {
// - selector: the first node at this CSS selector within the component
//
// The locus object can also specify a componentId. If it is not provided
- // (or it is invalid), we default to the currently active component, and
- // if that doesn't exist, we default to the very first component.
+ // we default to the currently active component, and if that doesn't exist,
+ // we default to the very first component.
//
// The locus result will be an object with the following properties:
//
@@ -391,6 +391,15 @@ Monocle.Book = function (dataSource) {
}
+ function isValidLocus(locus) {
+ if (!locus) { return false; }
+ if (locus.componentId && !componentIdMatching(locus.componentId)) {
+ return false;
+ }
+ return true;
+ }
+
+
function componentIdMatching(str) {
return p.componentIds.indexOf(str) >= 0 ? str : null;
}
@@ -403,6 +412,7 @@ Monocle.Book = function (dataSource) {
API.setOrLoadPageAt = setOrLoadPageAt;
API.chaptersForComponent = chaptersForComponent;
API.locusOfChapter = locusOfChapter;
+ API.isValidLocus = isValidLocus;
initialize();
View
16 src/core/reader.js
@@ -367,6 +367,13 @@ Monocle.Reader = function (node, bookData, options, onLoadCallback) {
if (!p.initialized) {
console.warn('Attempt to move place before initialization.');
}
+ if (!p.book.isValidLocus(locus)) {
+ dispatchEvent(
+ "monocle:notfound",
+ { href: locus ? locus.componentId : "anonymous" }
+ );
+ return false;
+ }
var fn = callback;
if (!locus.direction) {
dispatchEvent('monocle:jumping', { locus: locus });
@@ -376,20 +383,15 @@ Monocle.Reader = function (node, bookData, options, onLoadCallback) {
}
}
p.flipper.moveTo(locus, fn);
+ return true;
}
// Moves to the relevant element in the relevant component.
//
function skipToChapter(src) {
var locus = p.book.locusOfChapter(src);
- if (locus) {
- moveTo(locus);
- return true;
- } else {
- dispatchEvent("monocle:notfound", { href: src });
- return false;
- }
+ return moveTo(locus);
}

0 comments on commit c50bbf4

Please sign in to comment.
Something went wrong with that request. Please try again.