KnockOut Mapping Hierarchical JS object

*爱你&永不变心* 提交于 2019-12-21 20:43:13

问题


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 ,

here is some trial of mine , maybe will help to better understand my problem , http://jsfiddle.net/sureyyauslu/2wTjy/6/

Thanks a lot in advance...


回答1:


The problem was that you had a p tag nested within another. The template engine couldn't parse this incorrect markup.

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

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/

Hope this helps.



来源:https://stackoverflow.com/questions/9575267/knockout-mapping-hierarchical-js-object

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