Created
April 21, 2017 16:56
-
-
Save maynagashev/bb7d5ae88fd489c95b11c204da7d1638 to your computer and use it in GitHub Desktop.
Shared Object with History tracking methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Created by maynagashev on 21.04.17. | |
*/ | |
/** | |
* Shared Object for storing current Active Filter settings, used in: | |
* @components: moments-list, filter-bar, load-more | |
* | |
* + historyAPI (write and read new status) | |
* | |
* Initialization in moments-list's "created" hook | |
*/ | |
(function() { | |
var log = window.log.getLogger('moments:so-active-filter'); log.setDefaultLevel('debug'); | |
window.activeFilterSharedObject = { | |
data: { | |
category: '', | |
realm: '', | |
cam: '' | |
}, | |
set: function (filter, resetOthers, disableHistory) { | |
var self = window.activeFilterSharedObject, key; | |
for (key in self.data) { | |
self.data[key] = (filter.hasOwnProperty(key)) ? filter[key] : ((resetOthers) ? '' : self.data[key]); | |
} | |
if (!disableHistory) { | |
var history_url = self.updateHistory(self.data); | |
log.debug("[history] set url", history_url); | |
} | |
}, | |
get: function () { | |
var self = window.activeFilterSharedObject; | |
return self.data; | |
}, | |
/* | |
History API (browser): | |
1) update history when filter updated | |
2) fetch active filter from document.location when state changes | |
*/ | |
updateHistory: function (filters) { | |
function buildUrl(filters) { | |
var url = '/moments'; | |
filters = _.pick(filters, _.identity); | |
if (_.has(filters, 'realm')) { | |
url += '/' + filters.realm; | |
if (_.has(filters, 'cam')) { | |
url += '/' + filters.cam; | |
} | |
} | |
if (_.has(filters, 'category')) { | |
url += '?category=' + filters.category; | |
} | |
return url; | |
}; | |
var url = buildUrl(filters); | |
history.pushState(null, null, url); | |
return url; | |
}, | |
fetchFromLocation: function () { | |
var self = window.activeFilterSharedObject; | |
var url = document.location.href; | |
log.debug("[history] changed location to: " + url); | |
var filter = { | |
category: '', | |
realm: '', | |
cam: '' | |
}, m; | |
if (m = url.match(/(realm[0-9]+)/i)) | |
filter.realm = m[1]; | |
if (m = url.match(/(cam[0-9]+)/i)) | |
filter.cam = m[1]; | |
if (m = url.match(/category=([a-z0-9_\-]+)/i)) | |
filter.category = m[1]; | |
log.debug("[history] loaded filter from URL:", filter); | |
self.set(filter, true, true); | |
} | |
}; | |
// Event handler when user navigates through Back/Forward history buttons | |
window.onpopstate = function () { | |
window.activeFilterSharedObject.fetchFromLocation(); | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment