Created
March 26, 2015 09:34
-
-
Save victorpavlenko/8605641fa2f57b043e84 to your computer and use it in GitHub Desktop.
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
var HandlebarsService = (function(){ | |
const PATH_TO_TEMPLATE = '/js/templates/'; | |
var HandlebarsService = function() { | |
}; | |
$.extend(HandlebarsService.prototype, { | |
get: function(templateName, data) { | |
var compiled = ''; | |
templateName = templateName || ''; | |
data = data || {}; | |
$.ajax({ | |
url: this.getTemplateURL(templateName), | |
type: 'GET', | |
async: false, | |
dataType: 'json', | |
success: function(response) { | |
compiled = this.compile(response, data) | |
}.bind(this), | |
error: function(err) { | |
console.error(err) | |
}.bind(this) | |
}); | |
return compiled; | |
}, | |
getFromNode: function(selector, data) { | |
var $node = null; | |
selector = selector || ''; | |
data = data || {}; | |
if (typeof(selector) === 'string') { | |
$node = $(selector); | |
} else if (selector instanceof jQuery) { | |
$node = selector; | |
} | |
return this.compile($node.html(), data); | |
}, | |
getJQueryFromNode: function(selector, data) { | |
return $(this.getFromNode(selector, data)); | |
}, | |
compile: function(template, data) { | |
return Handlebars.compile(template)(data); | |
}, | |
getTemplateURL: function(template) { | |
var path = template || ''; | |
if (path[0] === '/') { | |
path = path.substr(1); | |
} | |
if (path.length < 5) { | |
path += '.hbs'; | |
} else if (path.substr(path.length - 4) !== '.hbs') { | |
path += '.hbs'; | |
} | |
console.log(PATH_TO_TEMPLATE + path); | |
return PATH_TO_TEMPLATE + path; | |
} | |
}); | |
return new HandlebarsService(); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment