Skip to content

Instantly share code, notes, and snippets.

@hutch120
Last active January 16, 2017 01:48
Show Gist options
  • Save hutch120/de38de5846a161dbe134df1f8983c883 to your computer and use it in GitHub Desktop.
Save hutch120/de38de5846a161dbe134df1f8983c883 to your computer and use it in GitHub Desktop.
Model Controller
'use strict'
/** USAGE **
HTML requires script:
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Attempts to load /config/mysite.json
Provides get/set methods using string paths
var siteName = "mysite"
PoziAPI()
.initalise(siteName)
.then(function () {
Model()
.debugconsole()
Model()
.set("config.someobject", {"foo": "bar"})
var someobject = Model()
.get("config.someobject")
.catch(function (err) {
debug("!!! ERROR !!! Initalising error occured: ", err)
})
*/
/**
* Global model object.
* ALWAYS access via Model Adapter functions.
* NEVER reference, read or update this object directly.
*/
var __GModelInternal = {} // ALWAYS access via Model Adapter functions.
/**
* Manages the model.
* Loads the siteconfig.
* Contains accessor functions to read and manipulate the model.
* May contain persistant functions in future, e.g. Read/Write from localstorage, etc.
*/
function Model() {
// Adapters
var adapters = {
'initalise': function (sitename) {
return initalise(sitename)
},
'get': function (path) {
return get(path)
},
'set': function (path, value) {
return set(path, value)
},
'debugconsole': function () {
return debugconsole()
}
}
/**
* Load Site Data and initalise class.
* See API.js for param details.
*
* @param {string} sitename
*
*/
var initalise = function (sitename) {
return new Promise(function (resolve, reject) {
if (__GModelInternal.loaded) {
debug("Site already initalised: ", sitename)
return resolve()
}
addUrlParametersToModel()
if (!sitename) {
// Check if sitename was in url
sitename = _.get(__GModelInternal, "url.site")
if (!sitename) {
// Check again if sitename was in url
return reject("Model initalise was unable to determine sitename!")
}
}
getSiteConfigFromServer(sitename, resolve, reject) // Consider this could save/load from localstorage.
})
}
/**
* Get url parameters from url as json object
*
* Uses lodash
* @returns {json} url parameters
*
*/
var addUrlParametersToModel = function () {
// Remove the '?' at the start of the string and split out each assignment
var urlParamsSearch = _.chain(location.search.slice(1)
.split('&'))
// Split each array item into [key, value]
// ignore empty string if search is empty
.map(function (item) {
if (item) return item.split('=');
})
// Remove undefined in the case the search is empty
.compact()
// returns an object composed from key-value pairs.
.fromPairs()
// Return the value of the chain operation
.value()
// Remove the '#' at the start of the string and split out each assignment
var urlParamsHash = _.chain(location.hash.slice(1)
.split('&'))
// Split each array item into [key, value]
// ignore empty string if search is empty
.map(function (item) {
if (item) return item.split('=');
})
// Remove undefined in the case the search is empty
.compact()
// Returns an object composed from key-value pairs.
.fromPairs()
// Return the value of the chain operation
.value()
var urlParams = _.merge(urlParamsSearch, urlParamsHash)
_.set(__GModelInternal, "url", urlParams)
}
/**
* Get siteconfig from server
*
* https://lodash.com/docs/4.17.4#get
* @param {string} url a value siteconfig url
* @returns {json} siteconfig
*
*/
var getSiteConfigFromServer = function (sitename, resolve, reject) {
var url = "/config/" + sitename + ".json"
debug("Get site data from site config:" + url)
$.ajax({
dataType: 'json',
url: url,
error: reject,
success: function (sc) {
_.set(__GModelInternal, "config", sc)
if (!__GModelInternal || !__GModelInternal.config.title) {
return reject("Invalid config file for site: " + sitename)
}
__GModelInternal.loaded = true
setDefaultData(sitename)
// debug(__GModelInternal)
return resolve()
}
})
}
/**
* Query the site config.
*
* https://lodash.com/docs/4.17.4#get
* @param {string} path
* @returns {object}
*
*/
var get = function (path) {
if (!__GModelInternal.loaded) {
debug("!!! ERROR !!! Model get called before initalise. Debug info: Model path requested: ", path)
return null
}
var value = _.get(__GModelInternal, path, null)
if (!value) {
debug("Model path not found", path)
}
return value
}
/**
* Set site config value
*
* https://lodash.com/docs/4.17.4#set
* @param {path} string
* @param {object} object
* @returns {object}
*
*/
var set = function (path, value) {
if (!__GModelInternal.loaded) {
debug("!!! ERROR !!! Model set called before initalise. Debug info: Model path requested: ", path)
return null
}
return _.set(__GModelInternal, path, value) // Lodash function
}
/**
* Set a default value if it doesnt exist in the config.
*
* https://lodash.com/docs/4.17.4#set
* @param {string} path
* @param {object} value
*
*/
var setDefault = function (path, value) {
if (!get(path, value)) {
debug("Model path " + path + " setting default to", value)
return set(path, value)
} else {
// Default value already set.
}
}
/**
* Output the current site config for debugging.
*/
var debugconsole = function () {
debug("Model object: ", __GModelInternal)
}
/**
* If no value exists in the config then set a default value.
*
* @param {string} sitename
*
*/
var setDefaultData = function (sitename) {
setDefault("sitename", sitename)
}
// Return adapters (must be at end of adapter)
return adapters
}
// End A (Adapter)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment