Created
November 13, 2014 23:35
-
-
Save arnogues/e98e173d7c89311c0462 to your computer and use it in GitHub Desktop.
Utils class, that need to be saved
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
'use strict'; | |
/* globals window, jQuery */ | |
(function ($) { | |
window.Utils = { | |
getOptionsFromDom: function (pluginName, element) { | |
element = $(element); | |
var pn = pluginName.toLowerCase(), | |
pnRe = new RegExp('^' + pn), | |
data = $(element).data() || {}, | |
options = {}, | |
_this = this, | |
optionsList = [pn, pn + 'Options']; | |
// check data-pluginname and data-pluginname-options | |
$.each(optionsList, function (i, name) { | |
if (data.hasOwnProperty(name)) { | |
$.extend(true, options, _this._parseJSON(data[name])); | |
} | |
}); | |
// check other data-pluginname-attributeXXX | |
$.each(data, function (i, obj) { | |
if (optionsList.indexOf(i) === -1) { | |
// set options[fooBar] = data[FooBar]; (transform FooBar into fooBar) | |
obj = _this._parseObject(obj); | |
if (obj !== '' && typeof(obj) !== 'undefined') { | |
options[_this._firstLetterLowerCase(i.replace(pnRe, ''))] = obj; | |
} | |
} | |
}); | |
return options; | |
}, | |
_firstLetterLowerCase: function (a) { | |
return a.toLowerCase(); | |
}, | |
_parseObject: function (obj) { | |
return typeof obj === 'string' && /^\{.*\}$/.test($.trim(obj)) ? this._parseJSON(obj) : obj; | |
}, | |
_parseJSON: function (str) { | |
try { | |
return (new Function('return ' + str))(); //jshint ignore:line | |
} catch (e) { | |
console.log(e); | |
return {}; | |
} | |
}, | |
substitute: function (string, object, regexp) { | |
return string.replace(regexp || (/\\?\{([^{}]+)\}/g), function (match, name) { | |
if (match.charAt(0) === '\\') { | |
return match.slice(1); | |
} | |
name = name.split('.'); | |
var tmpObj = object; | |
while (name.length) { | |
tmpObj = tmpObj[name.splice(0, 1)[0]]; | |
} | |
return (tmpObj !== null) ? (tmpObj || '') : ''; | |
}); | |
}, | |
getPositionInViewPort: function (elOrSelector) { | |
var el = $(elOrSelector); | |
var offset = el.offset(); | |
var $window = $(window); | |
var posX = offset.left - $window.scrollLeft(); | |
var posY = offset.top - $window.scrollTop(); | |
return { | |
left: posX, | |
top: posY, | |
height: el.outerHeight(), | |
width: el.outerWidth() | |
}; | |
}, | |
addSuffix: function (obj, suffix) { | |
for (var name in obj) { | |
if (obj.hasOwnProperty(name)) { | |
obj[name] = obj[name] + suffix; | |
} | |
} | |
return obj; | |
} | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment