当我使用knockout在我的视图模型中绑定数值数据时,它会正确显示,但如果用户更改输入标记值,则会将数据类型更改为字符串.提交字符串的问题是服务器需要一个没有隐式转换的数值.
有什么方法可以告诉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);
Run Code Online (Sandbox Code Playgroud)
RP *_*yer 49
这是一个包含一些不同技术的线程,以保持数值:https://groups.google.com/d/topic/knockoutjs/SPrzcgddoY4/discussion
一种选择是将此问题推入您的视图模型并创建一个numericObservable使用而不是正常的可观察对象.它可能看起来像:
ko.numericObservable = function(initialValue) {
var _actual = ko.observable(initialValue);
var result = ko.dependentObservable({
read: function() {
return _actual();
},
write: function(newValue) {
var parsedValue = parseFloat(newValue);
_actual(isNaN(parsedValue) ? newValue : parsedValue);
}
});
return result;
};
Run Code Online (Sandbox Code Playgroud)
示例:http://jsfiddle.net/rniemeyer/RJbdS/
另一种选择是使用自定义绑定来处理此问题.而不是使用的value绑定,您可以定义一个numericValue绑定,并用它来代替.它可能看起来像:
ko.bindingHandlers.numericValue = {
init : function(element, valueAccessor, allBindings, data, context) {
var interceptor = ko.computed({
read: function() {
return ko.unwrap(valueAccessor());
},
write: function(value) {
if (!isNaN(value)) {
valueAccessor()(parseFloat(value));
}
},
disposeWhenNodeIsRemoved: element
});
ko.applyBindingsToNode(element, { value: interceptor }, context);
}
};
Run Code Online (Sandbox Code Playgroud)
示例:http://jsfiddle.net/rniemeyer/wtZ9X/
| 归档时间: |
|
| 查看次数: |
10165 次 |
| 最近记录: |