Reputation: 409
var viewModel = {
foos: ko.observableArray([]),
reloadFoos: function () {
getFoos();
}
};
var foo = function () {
this.Id = ko.observable();
this.Name = ko.observable();
};
function getFoos() {
$.get("/myroute/", "", function (data) {
for (var i = 0; i < data.length; i++) {
var f = new foo();
f.Id = data[i].Id;
f.Name = data[i].Name;
viewModel.foos.push(f);
}
ko.applyBindings(viewModel);
});
}
<div data-bind="foreach: viewModel.foos">
<button data-bind="click : $parent.reloadFoos, attr: { id: Id }"></button>
<label data-bind="value: Name"></label>
</div>
Everything loads ok onload, but when I click the button, div label is blank and nothing is binded but I get no errors and seems to run through all the code.
Upvotes: 1
Views: 2795
Reputation: 22298
I created a fiddle with a few changes that makes this work: http://jsfiddle.net/johnpapa/dft3Z/
I admittedly cannot figure out exactly what you are trying to do. But the fiddle reads the array (which i I used an array instead of an ajax call just to keep ti local), and creates a series of buttons. It then binds the click event for each, which then adds a whole new set of buttons. There were a few problems with the code you had. The applyBindings should only happen once, the viewModel was already bound so the HTML did not need it specified, and the label should have been using the text binding, I suspect.
In any event, this does run now.
I still suspect this is not what you want. Perhaps if you explain what you are trying to accomplish, we can help further.
Upvotes: 1
Reputation: 2591
In the html you don't need the viewModel.
change it to this:
<div data-bind="foreach: foos">
<button data-bind="click : $parent.reloadFoos, attr: { id: Id }"></button>
<label data-bind="value: Name"></label>
</div>
UPDATE:
Ok, try it like this:
var foo = function (id, name) {
this.Id = ko.observable(id);
this.Name = ko.observable(name);
};
function getFoos() {
$.get("/myroute/", "", function (data) {
for (var i = 0; i < data.length; i++) {
var f = new foo(data[i].Id, data[i].Name);
viewModel.foos.push(f);
}
});
}
ko.applyBindings(viewModel);
html:
<div data-bind="foreach: viewModel.foos">
<button data-bind="click: $parent.reloadFoos, attr: { id: Id }"></button>
<label data-bind="value: Name"></label>
Take note that you need the ko.applyBindings(viewModel);
outside of the getFoos
function definition - currently you're rebinding every time it is called which is probably causing the disappearing
Upvotes: 0
Reputation: 193
I don't think reloadFoos is a parent of the foo Item in the foos array. Can you do something like this
for (var i = 0; i < data.length; i++) {
var f = new foo();
f.Id = data[i].Id;
f.Name = data[i].Name;
f.reloadFoos = function() { getFoos(); }
viewModel.foos.push(f);
}
Then have your click just call reloadFoos
Upvotes: 0