Reputation: 2116
If I have my model
function SearchModel() {
this.SearchCriteria = "";
}
and within my code have:
model.SearchCriteria = data;
ko.applyBindings(model);
and then in my html:
<select id="vehiclesMake" data-bind="options: SearchCriteria.Tool.VehicleMakes, optionsText: 'Description', value: SearchCriteria.Tool.SelectedModel, optionsCaption: 'Choose...'"></select>
all of which works fine. My dropdown gets populated as expected.
Now the problem I am having is when I add:
$('#vehiclesMake').change(function () {
loadSearchTool();
});
where loadSearchTool() does:
loadSearchTool = function () {
var postCode = $('#postcode').val();
var distance = $('#distance').val();
var make = $('#vehiclesMake').val();
var makemodel = $('#makemodel').val();
var minPrice = $('#minPrice').val();
var maxPrice = $('#maxPrice').val();
data.getQuickSearch(postCode, distance, make, makemodel, minPrice, maxPrice, function (data) {
//our success function
console.log(data.Result);
if (data.Result == 'Fail') {
console.log('Fail');//TO DO
}
else {
model.SearchCriteria = data;
ko.applyBindings(model);
}
}, function () {
console.log('error');//TO DO
});
};
With all the code above, when loadsearchtool(whichis also called on pageload) binds to the dropdown, the .change() code is firing and I end up in an infinite loop.
How can I get around this? This is my first crack at knockoutjs so am a bit of a newbie with it.
Upvotes: 0
Views: 175
Reputation: 18051
You just need to move ko.applyBindings(model);
outside loadSearchTool()
. ko.applyBindings should only be called once (from $(document).ready()
for example).
You probably also want to change SearchCriteria to an observable:
this.SearchCriteria = ko.observable("");
To update the data use:
model.SearchCriteria(data);
Upvotes: 1