如何在填充Json数据的剔除视图模型内部定义函数 [英] How to define function inside knockout viewmodel that is filled with Json data

查看:109
本文介绍了如何在填充Json数据的剔除视图模型内部定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在定义视图模型中的函数时遇到问题.

I am having issues with defining a function inside my viewmodel.

我通过jquery getJSON获取json数据并将其映射到我的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)
});

下面是我的视图模型.如您所见,我想通过称为companyName

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

然后,我想像<span data-bind="text: companyName" />一样使用此函数.但是,未评估JavaScript函数并以文本形式返回.

Then I want to use this function like <span data-bind="text: companyName" /> However, the JavaScript function is not evaluated and returned as text.

我在网络上浏览了Knockout的示例,但所有示例都使用了可计算的可观察对象.

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.

推荐答案

尝试一下:

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

这篇关于如何在填充Json数据的剔除视图模型内部定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆