KnockOut映射层次结构JS对象 [英] KnockOut Mapping Hierarchical JS object
问题描述
我正在尝试使用KnockOut映射插件创建视图模型
I am trying to create view Models using KnockOut mapping plugin ,
这是对象,基本上下面是一个带有单词的句子.
This is the object , Basically below is a sentence with words in it.
var data = {
name: 'Example Title',
sentences: [
{id: 1, words: [{text: 'word1'}, {text: 'word2'}]},
{id: 2, words: [{text: 'word3'}, {text: 'word4'}]}
]};
我想拥有三个视图模型,
I would like to have three view Models ,
文章应包含句子,句子应包含单词
Article should contain sentences , an Sentence should contain words
var ArticleViewModel = function(data)
{
var self = this;
self.id = ko.observable(data.id);
self.sentences = ko.observableArray([]);
}
var SentenceViewModel = function(data)
{
var self = this;
self.id = ko.observable(data.id);
self.words = ko.observableArray([]);
}
var WordViewModel = function(data)
{
var self = this;
self.id = ko.observable(data.id);
self.text = ko.observable(data.text);
}
我想将其放在视图"中,如下所示:
I would like to put this in View as below ;
<p data-bind="foreach:sentences">
<span data-bind="foreach:words">
<span data-bind="text:text">
</span>
</p>
我什至不确定我要实现的目标是否可行,但是我想我需要映射,但是我无法完成这项工作,
I am not even sure what I am trying to achieve is doable ,but I guess i need mappings , but I can not make this work ,
这是我的一些尝试,也许将有助于更好地了解我的问题, http://jsfiddle.net/sureyyauslu/2wTjy/6/
here is some trial of mine , maybe will help to better understand my problem , http://jsfiddle.net/sureyyauslu/2wTjy/6/
非常感谢...
推荐答案
问题是您将p标签嵌套在另一个标签中.模板引擎无法解析此错误的标记.
The problem was that you had a p tag nested within another. The template engine couldn't parse this incorrect markup.
当我认为您想要另一个foreach时,您还使用了with绑定.
You were also using a with binding when I think you wanted another foreach.
<p data-bind="foreach:sentences">
<span data-bind="text:id"></span>
<span data-bind="foreach:words">
<span data-bind="text:text"></span>
</span>
</p>
最后,句子模型可以简化为
Lastly the sentence model can be reduced to
var mySentenceModel = function(data) {
var self = this;
ko.mapping.fromJS(data, wordMapping, self);
}
您不需要定义id等,因为映射插件已将其全部处理.
You don't need to define the id etc as it's all taken care of by the mapping plugin.
http://jsfiddle.net/madcapnmckay/6hMA3/
希望这会有所帮助.
这篇关于KnockOut映射层次结构JS对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!