Created
October 15, 2012 09:09
-
-
Save kawasima/3891590 to your computer and use it in GitHub Desktop.
Handlebars template loader for backbone.js
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
;(function() { | |
var TemplateLoader = function() { | |
this.cache = {}; | |
this.prefix = "/"; | |
this.suffix = ".hbs"; | |
this.initialize.apply(this, arguments); | |
} | |
_.extend(TemplateLoader.prototype, {}, { | |
initialize: function() { | |
}, | |
config: function(options) { | |
if (options['prefix']) this.prefix = options['prefix']; | |
if (options['suffix']) this.suffix = options['suffix']; | |
}, | |
load: function(templateList, options) { | |
var self = this; | |
var unloadedTemplates = templateList.concat(); | |
$.each(templateList, function() { | |
var templateName = this.toString(); | |
$.ajax({ | |
url: self.prefix + templateName + self.suffix, | |
dataType: "text", | |
success: function(templateBody) { | |
self.cache[templateName] = Handlebars.compile(templateBody); | |
unloadedTemplates = _.without(unloadedTemplates, templateName); | |
if (unloadedTemplates.length == 0 && self.complete) | |
self.complete.call(self); | |
} | |
}); | |
}); | |
if (options['complete']) { | |
this.complete = options['complete']; | |
} | |
}, | |
get: function(templateName) { | |
return this.cache[templateName]; | |
}, | |
merge: function(templateName, context) { | |
return this.cache[templateName](context); | |
} | |
}); | |
Handlebars.TemplateLoader = new TemplateLoader(); | |
})(); |
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
Handlebars.TemplateLoader.load(["index", "list", "detail"], { | |
complete: function() { | |
var router = new Router(); | |
Backbone.history.start(); | |
} | |
}); | |
//---- | |
Handlebars.TemplateLoader.config({prefix: "/hbs/"}); | |
Handlebars.TemplateLoader.merge("index", {name: "hoge"}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment