Knockout.js 取消选中将复选框绑定到复杂对象并提交so服务器
我现在正在创建一组类似这样的复选框 一些背景: 起初,我专门为整个客户端VM使用ko.mapping插件 例如在我的代码上下文中:Knockout.js 取消选中将复选框绑定到复杂对象并提交so服务器,knockout.js,knockout-mapping-plugin,knockout-2.0,Knockout.js,Knockout Mapping Plugin,Knockout 2.0,我现在正在创建一组类似这样的复选框 一些背景: 起初,我专门为整个客户端VM使用ko.mapping插件 例如在我的代码上下文中: self.AllAgencyTypes = ko.mapping.fromJS([]); self.observables = { //this would be created by the mapping plugin on render/runtime SomeProperty: ko.observable(), AgencyTypes:
self.AllAgencyTypes = ko.mapping.fromJS([]);
self.observables = { //this would be created by the mapping plugin on render/runtime
SomeProperty: ko.observable(),
AgencyTypes: ko.observableArray()
}
我的复选框呈现正确,但屏幕加载时不会选中相应的复选框。然后我意识到了knockout中的一个问题,我需要将checked属性更改为text。(请参见我的get-ajax调用成功)
HTML
<tbody data-bind="foreach: AllAgencyTypes">
<tr>
<td>
<label class="checkbox inline">
<input type="checkbox" class="editorField" data-bind="attr: { value: Id },
checked: $root.SelectedAgencies" />
<span class="editorField" data-bind="text: Name"></span>
</label>
</td>
</tr>
</tbody>
我当前的问题是保存提交。因为我的复选框被绑定到新创建的可观察数组,所以它们没有绑定到我的服务器端模型
$.ajax({
url: options.editURL,
data: self.observables,
type: "post",
dataType: "json", ....
})
我有一个想法,如果我能做这样的事情。。。它可能会解决我的问题。。。但我不知道怎么做。(不允许获取.string/something错误。)
因此,我看到的唯一可用选项是将集合推回到由ko.mapping创建的原始对象中。。。我现在也不知道该怎么做。。。有什么想法吗?您正在寻找
ko.toJSON
,这是一个静态方法,可以返回任何对象的JSON版本以及可观察的成员!试试这个:
$.ajax({
url: options.editURL,
data: ko.toJSON(self.observables),
type: "post",
dataType: "json", ....
})
如果出于任何原因,您需要一个“纯JS”而不是一个序列化的JSON字符串,那么您可以使用ko.toJSON
本身使用的先行函数,ko.toJS
:
var plainJSVM = ko.toJS(self.observables); // this produces a JS object containing the current, primitive values of all observables, ready to be serialized as JSON.
选中的
绑定需要针对布尔值或数组进行绑定,因此不能直接针对字符串进行绑定
可以考虑对每个项目添加布尔值,并用A表示所选项目。
否则,您可以对您的所选代理机构
使用a来保持代理类型
的同步。我喜欢订阅的想法,明天我会尝试一下,并让您知道我的发现。。。
$.ajax({
url: options.editURL,
data: ko.toJSON(self.observables),
type: "post",
dataType: "json", ....
})
var plainJSVM = ko.toJS(self.observables); // this produces a JS object containing the current, primitive values of all observables, ready to be serialized as JSON.