https://stackoverflow.com/questions/75845300
by andrew rowe
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.1/knockout-latest.js"></script>
<button data-bind="click: clickNext">
Next
</button>
<button data-bind="click: clickPrevious">
Previous
</button>
<hr>
<img data-bind="attr: {src: story().image}">
<p data-bind="text: story().text"></p>
JavaScript
class ModelModel {
constructor() {
this.data = {
"1": {
"text": "Pick a chat",
"image": "http://placekitten.com/300/200",
"choices": [{
"choiceText": "Pick This",
"storyLink": "2"
}, {
"choiceText": "no pick this",
"storyLink": "3"
}, {
"choiceText": "nono this one",
"storyLink": "4"
}, {
"choiceText": "dont pick this",
"storyLink": "5"
}, ]
},
"2": {
"text": "Kittens",
"image": "https://placekitten.com/300/100",
"choices": [{
"choiceText": "Oops. Scared them.",
"storyLink": "3"
}]
},
"3": {
"text": "They are no longer scared",
"image": "https://placekitten.com/300/100",
"choices": [{
"choiceText": "Poor things.",
"storyLink": "3"
}]
},
};
this.currentIndex = ko.observable(1)
this.story = ko.observable(this.data[this.currentIndex().toString()]);
}
clickNext() {
this.currentIndex(this.currentIndex() + 1);
this.story(this.data[this.currentIndex().toString()])
}
clickPrevious() {
this.currentIndex(this.currentIndex() - 1);
this.story(this.data[this.currentIndex().toString()])
}
}
const model = new ModelModel();
window.addEventListener('load', () => {
ko.applyBindings(model);
});