I'm using Pager JS, Knockout and Jquery in my web application. Here's the code
function ViewModel(){
var self = this;
self.interior = ko.observable();
self.interior.background = ko.computed(function() {
$.getJSON('/interiors', {interior_id: self.interior_id()}).success(function(data) {
return self.interior.background = data.interior.background_url;
});
}, this);
}
$(document).ready(function () {
pager.Href.hash = "#!/";
viewModel = new ViewModel();
pager.extendWithPage(viewModel);
ko.applyBindings(viewModel);
pager.start();
});
When the code is executed I get the following error:
Uncaught TypeError: Object #<ViewModel> has no method 'interior_id'
I understand that the variable does not exist yet, and she do not have a method. But how to get around this error?
If the interior_id
gets added to your viewmodel later then you can use the deferEvaluation
option on your ko.computed
so it only evaluates its function when the background
property gets accessed and not when your ViewModel
is created:
self.interior.background = ko.computed(function() {
//do stuff
}, this, {deferEvaluation: true});