2

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.

emre nevayeshirazi
  • 18,983
  • 12
  • 64
  • 81

2 Answers2

4

Try this:

var CompanyViewModel = function(data) {
    ko.mapping.fromJS(data, {}, this); 
};

CompanyViewModel.prototype.fileTaxes = function() {
    console.log("Company is filing taxes.");
};

$.getJSON('/Company/GetCompanies', function(data) { 

    // data would look something like this: 
    // data: { companyName : "MicroStrategy",
    //         founderName : "etc" }
    var viewModel = new CompanyViewModel(data);
    ko.applyBindings(viewModel)
});
Paolo del Mundo
  • 2,121
  • 13
  • 18
  • where is the company function ? I am trying to define a function inside viewmodel. – emre nevayeshirazi Jul 05 '12 at 19:00
  • I've edited the original code to include an example of adding a method to the class CompanyViewModel (it's called fileTaxes). You don't need to create the companyName function anymore, as it is handled by the ko.mapping.fromJS function. – Paolo del Mundo Jul 06 '12 at 19:45
1

I've made some test, and this works for me:

return self.model()[0].CompanyName;

And call it with: data-bind="text: companyName()"

EDIT:

       var CompanyViewModel = function() {
            var self = this;

            self.companyName = function(){

                 return self.model()[0].CompanyName; 
            };
        }

        $.getJSON('/Company/GetCompanies', function(data) { 
            var viewModel = new CompanyViewModel();
            viewModel.model = ko.mapping.fromJS(data);
            ko.applyBindings(viewModel);
        });

This works assuming that your JSON data is returned in a format like:

[{"CompanyName":"Stack","SomeOtherField":"SomeOtherValue"},...];

and that you have only one company inside it.

Ingro
  • 2,841
  • 5
  • 26
  • 42