Skip to content

Instantly share code, notes, and snippets.

@rogersillito
Last active November 20, 2015 16:15
Show Gist options
  • Save rogersillito/75494dfbdfb33c204587 to your computer and use it in GitHub Desktop.
Save rogersillito/75494dfbdfb33c204587 to your computer and use it in GitHub Desktop.
knockout.js: toggle/toggleable components
<!DOCTYPE html>
<html>
<head>
<script src="
https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-debug.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<nu-toggle params="toggleId: 'toggle1', text: 'toggle1 now!'"></nu-toggle>
<nu-toggle params="toggleId: 'toggle2', text: 'toggle2 now!'"></nu-toggle>
<nu-toggleable params="toggleId: 'toggle1'">
<h3>I'm toggled by <u>toggle1</u></h3>
</nu-toggleable>
<nu-toggleable params="toggleId: 'toggle1'">
<h3>I'm also toggled by <u>toggle1</u></h3>
</nu-toggleable>
<nu-toggleable params="toggleId: 'toggle2'">
<h3>I'm toggled by <u>toggle2</u></h3>
</nu-toggleable>
<script id="jsbin-javascript">
ko.postbox = new ko.subscribable();
ko.components.register('nu-toggle', {
viewModel: function(params) {
var self = this;
self.toggleId = params.toggleId;
self.text = params.text;
self.toggle = function() {
ko.postbox.notifySubscribers(self.toggleId, "toggling");
};
},
template:
'<input type="button" data-bind="click: toggle, value: text" />'
});
ko.components.register('nu-toggleable', {
viewModel: function(params) {
var self = this;
self.toggleId = params.toggleId;
self.toggled = ko.observable(true);
self.toggle = function(togglingId) {
if (togglingId === self.toggleId) {
self.toggled(!self.toggled());
}
};
ko.postbox.subscribe(self.toggle, null, "toggling");
},
template: '<div data-bind="visible: toggled, template: { nodes: $componentTemplateNodes }"></div>'
});
ko.applyBindings({});
</script>
<script id="jsbin-source-javascript" type="text/javascript">ko.postbox = new ko.subscribable();
ko.components.register('nu-toggle', {
viewModel: function(params) {
var self = this;
self.toggleId = params.toggleId;
self.text = params.text;
self.toggle = function() {
ko.postbox.notifySubscribers(self.toggleId, "toggling");
};
},
template:
'<input type="button" data-bind="click: toggle, value: text" />'
});
ko.components.register('nu-toggleable', {
viewModel: function(params) {
var self = this;
self.toggleId = params.toggleId;
self.toggled = ko.observable(true);
self.toggle = function(togglingId) {
if (togglingId === self.toggleId) {
self.toggled(!self.toggled());
}
};
ko.postbox.subscribe(self.toggle, null, "toggling");
},
template: '<div data-bind="visible: toggled, template: { nodes: $componentTemplateNodes }"></div>'
});
ko.applyBindings({});</script></body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment