Skip to content

Instantly share code, notes, and snippets.

@guyjacks
Last active May 2, 2016 19:03
Show Gist options
  • Save guyjacks/5a8763ff71f90e3fe8b4b153ed9a5283 to your computer and use it in GitHub Desktop.
Save guyjacks/5a8763ff71f90e3fe8b4b153ed9a5283 to your computer and use it in GitHub Desktop.
<html>
<head>
<title>Knockout Tutorial</title>
</head>
<body>
<badge-button params="badge: oarBadge"></badge-button>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js'></script>
<script>
function Badge(name, has, active) {
var self = this;
self.name = ko.observable(name);
self.has = ko.observable(has);
self.active = ko.observable(active);
self.disabled = ko.computed(function() {
return self.has();
});
self.toggleActive = function() {
self.active(!self.active())
};
self.toggleHas = function() {
self.has(!self.has());
};
}
function AppViewModel() {
var self = this;
self.oarBadge = ko.observable();
$.getJSON('/guy.json', function(data) {
var badge = new Badge('wood oar', data.badges.oar, false);
self.oarBadge(badge);
// self.oarBadge().has() returns true so the badge is being properly created with data
// returned by the ajax call
});
} // AppViewModel()
ko.components.register('badge-button', {
viewModel: function(params) {
var self = this;
self.badge = params.badge();
self.open = function() {
self.badge.toggleHas();
self.badge.toggleActive();
}
},
template:
'<img class="ui image" src="http://fakeimg.pl/300/" data-bind="click: open, css: { disabled: badge.disabled }" >'
});
ko.applyBindings(new AppViewModel());
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment