KnockoutJS bind document title and stylesheets
by robatwilliams
HTML
<div>
Enter document title: <input data-bind="value: title, valueUpdate: 'afterkeydown'" />
</div>
<div>
Select theme: <select data-bind="options: themes, optionsText: 'name', value: selectedTheme"></select>
</div>
<div class="ui-widget-content"></div>
CSS
.ui-widget-content {
width: 100px;
height: 100px;
}
JavaScript
var vm, titleElement, themeLink;
vm = {
title: ko.observable(),
selectedTheme: ko.observable(),
themes: [
{
name: 'black-tie',
url: 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/black-tie/jquery-ui.min.css'
}, {
name: 'le-frog',
url: 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/le-frog/jquery-ui.min.css'
}
]
};
vm.selectedTheme(vm.themes[0]);
titleElement = document.querySelector('title');
titleElement.setAttribute('data-bind', 'text: title');
themeLink = document.createElement('link');
themeLink.setAttribute('rel', 'stylesheet');
themeLink.setAttribute('data-bind', 'attr: { href: selectedTheme().url }');
document.head.appendChild(themeLink);
ko.applyBindings(vm, titleElement);
ko.applyBindings(vm, themeLink);
ko.applyBindings(vm, document.body);