Skip to content

Instantly share code, notes, and snippets.

@khornberg
Created December 10, 2020 19:40
Show Gist options
  • Save khornberg/2e182a8471b05866b16437a9bf2e3df8 to your computer and use it in GitHub Desktop.
Save khornberg/2e182a8471b05866b16437a9bf2e3df8 to your computer and use it in GitHub Desktop.
Knockout and Vue - it's "just" JavaScript :)
<html>
<head>
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-min.js'></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
<p>
Demonstrates that knockout and vue and communicate data between the two frameworks
<br>
The data and shared functions are shown as pure javascript objects or functions
<br>
The <code>Save</code> button is rendered from Vue. It receives the number of points selected from the knockout application/form.
</p>
<hr>
<h3 data-bind="text: question"></h3>
<p>Please distribute <b data-bind="text: pointsBudget"></b> points between the following options.</p>
<table>
<thead><tr><th>Option</th><th>Importance</th></tr></thead>
<tbody data-bind="foreach: answers">
<tr>
<td data-bind="text: answerText"></td>
<td><select data-bind="options: [1,2,3,4,5], value: points"></select></td>
</tr>
</tbody>
</table>
<h3 data-bind="visible: pointsUsed() > pointsBudget">You've used too many points! Please remove some.</h3>
<p>You've got <b data-bind="text: pointsBudget - pointsUsed()"></b> points left to use.</p>
<div id="app-5">
<p> In Vue, will react to state changes from Knockout</p>
<button v-on:click="save" v-bind:disabled="!enable">Vue Save</button>
</div>
<script>
var points = 10;
var Model = {
enable: false,
points: points,
}
function Save() {
alert(`Used ${this.model.points} points so far`)
}
</script>
<script>
var app5 = new Vue({
el: '#app-5',
data: {
model: Model,
enable: null,
},
methods: {
save: Save
},
watch: {
'model.enable': function() {
this.enable = this.model.enable
}
}
})
</script>
<script>
function Answer(text) { this.answerText = text; this.points = ko.observable(1); }
function SurveyViewModel(question, pointsBudget, answers, Model) {
this.question = question;
this.pointsBudget = pointsBudget;
this.answers = answers.map(function(text) { return new Answer(text) });
this.pointsUsed = ko.computed(function() {
var total = 0;
for (var i = 0; i < this.answers.length; i++)
total += this.answers[i].points();
Model.enable = total <= this.pointsBudget;
Model.points = total
return total;
}, this);
}
var answers = [
"Functionality, compatibility, pricing - all that boring stuff",
"How often it is mentioned on Hacker News",
"Number of gradients/dropshadows on project homepage",
"Totally believable testimonials on project homepage"
]
ko.applyBindings(new SurveyViewModel("Which factors affect your technology choices?", points, answers, Model));
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment