0

我想在 knockout.js 中模仿一个复杂的模型:

function DefInfo(dfirst, dlast) {
    this.dfirst = ko.observable(dfirst);
    this.dlast = ko.observable(dlast);
}

function PaymentViewModel() {
     var self = this;
     self.pmt = ?? (where pmt.defInfo = DefInfo, pmt.contact = ContactInfo, etc
}

基本上我要做的是使用 ko.toJson(pmt); 传回 json;

这可能吗?

谢谢

4

2 回答 2

0

当然可以有嵌套的 viewModel 对象。

尝试类似:

function DefInfo(dfirst, dlast) {
    this.dfirst = ko.observable(dfirst);
    this.dlast = ko.observable(dlast);
}

function Payment(defInfo, contactInfo) {
    this.defInfo = ko.observable(defInfo);
    this.contactInfo = ko.observable(contactInfo);
}

function PaymentViewModel() {
     var self = this;
     self.pmt = ko.observable(new Payment(new DefInfo("a", "b"), new ContactInfo()));
}

如果你不需要它们是可观察的,你甚至可以做一些简单的事情,比如:

function PaymentViewModel() {
     var self = this;
     self.pmt = {
         defInfo: new DefInfo("a", "b"),
         contact: new ContactInfo()
     };
}
于 2015-01-11T01:10:48.000 回答
0

好的 - 我尝试了您的代码,但无法在 html 中正确绑定。这是我所拥有的:

   <div class="panel panel-body`">

<fieldset>
    <legend>Defendant Information</legend>
    <div class="form-group">
        <label for="dfirst">First Name:</label>
        <input data-bind="text: dfirst" type="text" id="dfirst" />
    </div>
    <div class="form-group">
        <label for="dlast">Last Name:</label>
        <input data-bind="text: dlast" type="text" id="dlast" />
    </div>
</fieldset>

<button data-bind="click: makePayment" class="btn btn-default">Make Payment</button>
 </div>   

当我输入值并单击 makePayment 按钮时 - 我检查了 pmt.defInfo 的值,它们仍然是空白的。

谢谢。

于 2015-01-11T21:30:17.820 回答