Created
March 4, 2013 18:13
-
-
Save robdodson/5084211 to your computer and use it in GitHub Desktop.
knockout.templates
This file contains hidden or 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
| require([ | |
| 'jquery', | |
| 'lodash', | |
| 'knockout', | |
| 'models/AppViewModel', | |
| 'bootstrap' | |
| ], function($, _, ko, AppViewModel) { | |
| // Document Ready | |
| $(function() { | |
| function initialize() { | |
| console.log('templates loaded. starting application...'); | |
| var appViewModel = new AppViewModel(); | |
| ko.applyBindings(appViewModel); | |
| } | |
| // Manage the loading of the templates | |
| // When returning the template, return its name as well | |
| function getTemplate(url) { | |
| var dfd = new $.Deferred(), | |
| name = _.last(url.split('/')), | |
| $ajax = $.ajax(url); | |
| $ajax.done(function(tmpl) { | |
| dfd.resolve(tmpl, name); | |
| }); | |
| return dfd.promise(); | |
| } | |
| // Sends each String in the Array to $.ajax to load the template | |
| // Returns an Array of jQuery Deferreds | |
| var queue = _.map([ | |
| './templates/button/button.anchor.tmpl', | |
| './templates/button-dropdown/button.dropdown.tmpl', | |
| './templates/checkbox/checkbox.tmpl', | |
| './templates/heading/heading.h1.tmpl', | |
| './templates/masthead/masthead.tmpl' | |
| ], getTemplate); | |
| // When each template finishes loading, append it to the page | |
| _.each(queue, function(promise) { | |
| promise.done(function(tmpl, name) { | |
| var script = document.createElement('script'); | |
| script.type = 'text/html'; | |
| script.id = name; | |
| script.innerHTML = tmpl; | |
| $('body').append(script); | |
| }); | |
| }); | |
| // When the queue is finished kickoff the application | |
| // We can't pass an Array to $.when because it expects comma | |
| // separated arguments. So use Function.apply | |
| $.when.apply(null, queue).then(initialize); | |
| }) | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment