我是Knockout JS的新手。我没有通过谷歌在与淘汰赛js的映射上找到很多帮助。我有一个来自服务器的JSON。我使用knockout js映射库映射JSON。与属性关联的数据绑定dom不会更新。 我已经包含了一个使用脚本的小提琴。 注意json对象被映射到observable。单击加载按钮时,将映射json,并且属性“test”的值应显示在标记中。任何想法为什么它没有出现在标签中?
JS小提琴中有一个有效的例子。
这是正在映射的JSON
var json = {
"id": 9,
"test": "John Doe",
"firstName": "John",
"lastName": "Doe",
"referenceNumber": "BUY-08",
"position": "Buyer",
"type": "Buyer",
"telephone": "028 82 240780",
"email": "m@email.com",
"departmentId": 3,
"departmentName": "DEPT B",
"country": "United Kingdom"
};
我的示例脚本
var masterModel = function()
{
var self = this;
self.members = ko.observableArray([]);
self.websites = ko.observableArray([]);
self.seoData = ko.observable();
self.test = ko.observable();
self.loadWebsite = function(website)
{
var json = {
"id": 9,
"test": "John Doe",
"firstName": "John",
"lastName": "Doe",
"referenceNumber": "BUY-08",
"position": "Buyer",
"type": "Buyer",
"telephone": "028 82 240780",
"email": "m@email.com",
"departmentId": 3,
"departmentName": "DEPT B",
"country": "United Kingdom"
};
self.test(ko.mapping.fromJS(json))
console.log(self.test);
}
}
var master = new masterModel();
ko.applyBindings(master);
问题是当你点击loadWebsite时,$ data.test.test没有更新!
答案 0 :(得分:2)
我更新了,似乎有一些小的改动:
关键是我解除了'test'可观察性:
<h1 data-bind="text: test().test">?</h1>
我还初始化了初始值:
self.test = ko.observable({ test: ko.observable('WTF') });