lundi 12 janvier 2015

Parse URL and load corresponding data

I’ve successfully implemented routing and hashing with crossroadsJS and hasherJS on a SPA I’m working on. The data I’m loading from a REST API is entirely event based. This works fine for navigating through the website with click based events. However, I want to implement the ability to type in a URL (or refresh the current view) and load the data corresponding to that URL. I wrote a method like this:



// app.js
app.helpers = {
routeMagic: function (prop, clicked, type, el) {
var parser = document.createElement('a'); // setup parsing
parser.href = hasher.getURL(); // use hasher's .getURL() to find current URL
var splitURL = parser.hash.split('/')[2]; // split at second / ... example: /conditions/annual-wellness-exam => annual-wellness-exam

propArr = []; // set up array to store name property
for (var i=0, len=prop.length; i<len; i++) {
propArr.push(prop[i].name.replace(/,/g, "").replace(/\//g, "").replace(/[()]/g, "").replace(/\s+/g, "-").toLowerCase());
}

$(el).each(function () { // target li ... example ‘.returned-list li’
var val = $(this);
val.id = propArr; // append name to li id
var id = $(this).attr('id');

// this is only executing on click event, need it to execute on refresh or typing in URL
if (splitURL === id) { // find a match
console.log('match found');
clicked = val.children().attr('data-id'); // determine where to route the page to based off data-id

return false;
}
});
type(clicked); // init crossroads routing
}
};


Which would be called like so:



// routes.js
conResultsRoute = crossroads.addRoute('conditions/{name}', function () {
app.helpers.routeMagic(cache.lists.conditions, cache.justClickedCondition, api.endpoints.condition, '.returned-list li');
});


For this example, when I click on a ‘conditions’ link from a list of conditions, the expected results are returned on the following route. However, if I try to type in the same URL, I get a list back of all the data stored in the CMS rather than my filtered list like when I click through the app. I think the problem stems from not being able to target my $(el).each() on page load since it’s held in a different template, or possibly I have to reload my API calls every time I type in a URL. I imagine this isn’t enough data for someone to troubleshoot, so feel free to ask me more questions or check out a live (in development) version here


If you’re visiting the website, try a flow like this: Conditions (main nav) -> Annual Wellness Exam -> Refresh or hit enter in URL bar


Aucun commentaire:

Enregistrer un commentaire