简体   繁体   English

ViewModel 上的 Knockoutjs 绑定输入

[英]Knockoutjs binding input on ViewModel

I have a knockout.js ViewModel named CreateVM contains other ViewModel - FrmAddGoodsVM.我有一个名为 CreateVM 的 knockout.js ViewModel 包含其他 ViewModel - FrmAddGoodsVM。 The problem is when I binding some input into FrmAddGoodsVM, the input will show [object HTMLInputElement].问题是当我将一些输入绑定到 FrmAddGoodsVM 时,输入将显示 [object HTMLInputElement]。 Can someone show me what I've missed?有人可以告诉我我错过了什么吗?

I've put these input bindings from FrmAddGoodsVM to CreateVM and it worked fine.我已经将这些输入绑定从 FrmAddGoodsVM 放到了 CreateVM 中,它运行良好。 But I want to bind them from FrmAddGoodsVM and don't know why it does not work.但我想从 FrmAddGoodsVM 绑定它们,不知道为什么它不起作用。

index.js index.js

function FrmAddGoodsVM() {
    let self = this; 
    self.frmName = ko.observable(null);
    self.frmAddress = ko.observable(null);
}

function CreateVM() {
    let self = this;
    ...
    self.FrmAddGoodsVM = new FrmAddGoodsVM();
}

$(document).ready(function() {
    let createVM = new CreateVM();
    ko.applyBindings(createVM, document.getElementById('create'))
})

index.html索引.html

<form role="form">
    <input id="frmName" data-bind="value: frmName"/>
    <input id="frmName" data-bind="value: frmAddress"/>
</form>

Expected output: The input elements will not have value [object HTMLInputElement]预期的 output:输入元素将没有值 [object HTMLInputElement]

I'm not really sure what's happening, but you're basically off by one on your object nesting.我不太确定发生了什么,但你的 object 嵌套基本上是差了一个。 Create VM has a property that is the real VM. Create VM 具有一个属性,即真正的 VM。 So you just need to adjust your binding and Tada!所以你只需要调整你的绑定和多田!

 function FrmAddGoodsVM() { let self = this; self.frmName = ko.observable(""); self.frmAddress = ko.observable(""); } function CreateVM() { let self = this; self.FrmAddGoodsVM = new FrmAddGoodsVM(); } let createVM = new CreateVM(); ko.applyBindings(createVM.FrmAddGoodsVM)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> <form role="form"> <input id="frmName" data-bind="value: frmName"/> <input id="frmName" data-bind="value: frmAddress"/> </form>

On a side note, bringing jquery in for one single feature is pretty wasteful, especially when knockout is just fine loading at the end of the dom, or you could just use the vanilla version, OnContentReady .附带说明一下,将 jquery 引入单个功能是非常浪费的,尤其是当淘汰赛在 dom 末尾加载时很好,或者您可以只使用香草版本OnContentReady

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM