如何通过“可观察对象”创建(映射)复杂类型Knockout.js

How to create ("map") complex types through "observables" with Knockout.js?

本文关键字:映射 复杂 类型 js Knockout 创建 何通过 观察 可观察对象 对象      更新时间:2023-09-26

所以,我正在学习knockout.js,我对如何在其中创建嵌套的复杂类型有点困惑。

例如,在服务器端,我的模型是:
class Person {
public string Name {get; set;}
public int Age {get; set;}
public List<Colors> FavoriteColors {get; set;}
}
class Color {
public int ColorId {get; set;}
public string Name {get; set;}
}

asp.net mvc输出的JSON类似于(如果我输出一个List<Person>类型):

[{"Name":"JC","Age":24,"Colors":[{"ColorId":1,"Name":"Red"},{"ColorId":2,"Name":"Blue"}]},
{"Name":"Albert","Age":29,"Colors":{"ColorId":2,"Name":"Blue"}}]

现在我想通过可观察对象映射,通过Jquery Ajax获得。我知道FavoriteColors将是一个数组,但我有点困惑的事情将如何锻炼在这里…

任何帮助都将非常感激!

更新:

有谁能帮我一下吗?(我做了一个原型,但我的选择不起作用)

http://jsbin.com/eqihun/3/edit javascript、html、生活

看看knockout mapping插件

链接到解决方案:here

$(document).ready(function(){
  //document.writeln(data[0].Colors[0].Name);
  //if I map anything to ko.observable, it would be sent through ko.toJSON... so that means that Color stuff should NOT be mapped, especially because that's not what MVC is asking, but rather List<Colors>...
  var Color = function (id, name) {
     var self = this;
     self.colorId = id;
     self.name = name;
  };
 function viewModel() {
    var self = this;
    self.Name = ko.observable("Bert");
    self.Age = ko.observable('12');
    self.FavoriteColors = ko.observableArray([
      new Color(1, "Blue"), 
      new Color(2, "Red"), 
      new Color(3, "White")
    ]);
  } 
  ko.applyBindings(new viewModel());    
});
HTML:

<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
  <script src="https://raw.github.com/SteveSanderson/knockout/master/build/output/knockout-latest.debug.js" type="text/javascript"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
</style>
</head>
<body>
  <p>Name: <input type="text" data-bind="value: Name" name="Name"></p>
  <p>Age: <input type="text" data-bind="value: Age" name="Name"></p>

  <select data-bind="options: FavoriteColors, optionsText: 'name', value: 'colorId', optionsCaption: 'Choose...'"></select>