使用json初始化KnockOut模型

时间:2013-08-22 18:12:01

标签: javascript knockout.js

我想使用从服务器收到的json初始化Knockout模型。

目前,我有这个HTML:

<div class='liveExample'>   
    <p>First name: <input data-bind='value: firstName' /></p> 
    <p>Last name: <input data-bind='value: lastName' /></p> 
    <h2>Hello, <span data-bind='text: fullName'> </span>!</h2>  
</div>

这个JavaScript:

// Here's my data model
var ViewModel = function(first, last) {
    this.firstName = ko.observable(first);
    this.lastName = ko.observable(last);

    this.fullName = ko.computed(function() {
        return this.firstName() + "/" + this.lastName();
    }, this);
};

var viewModel = new ViewModel();
data = { firstName: 'test', lastName: 'bla' }; //received from the server side

viewModel.firstName(data.firstName)
viewModel.lastName(data.lastName)

ko.applyBindings(viewModel);

它有效,但如果我有更多的领域,它会很痛苦。

我尝试使用这样的映射插件:

var viewModel = new ViewModel();
data = { firstName: 'test', lastName: 'bla' }; //received from the server side

viewModel = ko.mapping.fromJSON(data, viewModel)

ko.applyBindings(viewModel);

在这种情况下,方法fullName未定义。

我试着这样做:

viewModel = ko.mapping.fromJSON(viewModel, data)

lastNamefirstName未定义。

有一个简单的解决方案吗?

谢谢!

3 个答案:

答案 0 :(得分:4)

您需要使用ko.mapping.fromJS(),因为您正在使用真正的JavaScript对象。

ko.mapping.fromJSON()方法适用于使用JSON字符串的情况。例如:

'{ "firstName": "test", "lastName": "bla" }'

答案 1 :(得分:0)

如果data的属性名称和相应的viewModel可观察名称相同,则可以使用以下代码。

var viewModel = new ViewModel();
for(var prop in data)
viewModel[prop](data[prop]);

ko.applyBindings(viewModel);

答案 2 :(得分:0)

只有淘汰赛:

var ViewModel = function(data) {
    var self = this;
    self.firstName = ko.observable(data.first);
    self.lastName = ko.observable(data.last);

    self.fullName = ko.computed(function() {
        return self.firstName() + "/" + self.lastName();
    });
};

var data = {first: 'lorem', last: 'ipsum'};
ko.applyBindings(new viewModel(data));

淘汰+ ko.mapping

var ViewModel = function(data) {
    var self = this;
    ko.mapping.fromJS(initData, {}, self);

    self.fullName = ko.computed(function() {
            return self.firstName() + "/" + self.lastName();
    });
};

var data = {first: 'lorem', last: 'ipsum'};
ko.applyBindings(new viewModel(data));