I've been playing around with KnockoutJS in order to gain a better understanding of how it works, which eventually leads to some unconventional coding.
This is the script:
var ViewModel = function() {
var self = this;
self.counter = ko.observable(0);
self.someFruits = ko.observableArray();
self.createbox = function (){
var value = {
name: self.counter(),
isChecked: ko.observable(true)
};
self.someFruits.push(value);
$("#div1").append('<div><input type="checkbox" data-bind="checked: someFruits()[' + self.counter() + '].isChecked" /> Cherry</div>');
$("#div2").append('<div><input type="checkbox" data-bind="checked: someFruits()[' + self.counter() + '].isChecked" /> Cherry</div>');
self.counter(self.counter() + 1);
}
};
ko.applyBindings(new ViewModel());
And here is the HTML:
<div>
<div>
<button data-bind="click: createbox" type="button" class="btn btn-warning">Create Box</button>
</div>
<div id="div1">
</div>
<br>
<br>
<div id="div2">
</div>
</div>
What I'm trying to simulate is the functionality to dynamically create check-boxes that will be data-bound to an observable object inside an observable-array. So I made a button that will push
a new object that will contain a ko.observable
into an observableArray
. Then use Jquery to append html markups for the checkbox. I append two identical checkboxes each time to different div
just to see if they are updating according to the bound object.
It is brutish, and ideally I shouldn't use JQuery for these purposes, and perhaps a foreach
would be nice here. But I'd still like to understand why this isn't working, when I thought it should.
Aucun commentaire:
Enregistrer un commentaire