【发布时间】:2011-11-15 19:02:12
【问题描述】:
当我使用敲除在我的视图模型中绑定数字数据时,它会正确显示,但如果用户更改输入标记值,则会将数据类型更改为字符串。提交字符串的问题是服务器需要一个没有隐式转换的数值。
有什么方法可以告诉knockout保持原始属性值的数据类型?
我的示例代码将视图模型名称与输入标签名称相匹配。我使用不显眼的敲除来进行绑定,效果很好。
// Bind the first object returned to the first view model object
// FNS is the namespace, VM is the view model
FNS.VM.Items[0] = ko.mapping.fromJS(data.Items[0]);
// For each property found, find the matching input and bind it
$.each(FNS.VM.Items[0], function (indexInArray, valueOfElement) {
var attrName = indexInArray;
var attrValue;
if (typeof valueOfElement == "function")
attrValue = valueOfElement();
else
attrValue = valueOfElement;
var a = $('input[name="' + attrName + '"][type="checkbox"]');
if (a.length)
a.dataBind({ checked: 'VM.Items[0].' + attrName });
var b = $('input[name="' + attrName + '"][type="radio"]');
if (b.length)
b.dataBind({ checked: 'VM.Items[0].' + attrName });
var c = $('input[name="' + attrName + '"][type="text"]');
if (c.length)
c.dataBind({ value: 'VM.Items[0].' + attrName });
});
ko.applyBindings(FNS);
【问题讨论】:
标签: knockout.js