How to define function inside knockout viewmodel that is filled with Json data

旧巷老猫 提交于 2019-12-11 01:55:39

问题


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.



来源:https://stackoverflow.com/questions/11343494/how-to-define-function-inside-knockout-viewmodel-that-is-filled-with-json-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!