How to define function inside knockout viewmodel t

2019-07-11 18:04发布

问题:

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.

回答1:

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)
});


回答2:

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.