I am having issues with defining a function inside my viewmodel.
I fetch json data via jquery getJSON and map this data to my viewmodel.
$.getJSON('/Company/GetCompanies', function(data) {
var viewModel = new CompanyViewModel()
viewModel.model = ko.mapping.fromJS(data)
ko.applyBindings(viewModel)
});
Below is my viewmodel. As you can see what I want to do is, returning one of the properties of viewmodel via function called companyName
var CompanyViewModel = function() {
var self = this;
self.companyName = function()
return model.CompanyName;
};
}
Then I want to use this function like <span data-bind="text: companyName" />
However, the JavaScript function is not evaluated and returned as text.
I go through the examples of Knockout on the web, but all of them are using computed observables.
Is there a way to achive this ? Thanks.
Try this:
I've made some test, and this works for me:
return self.model()[0].CompanyName;
And call it with:
data-bind="text: companyName()"
EDIT:
This works assuming that your JSON data is returned in a format like:
and that you have only one company inside it.