Knockout.js:时间输入格式和值限制 [英] Knockout.js: time input format and value restriction
问题描述
当我使用敲除将数字数据绑定到视图模型中时,它可以正确显示,但如果用户更改输入标签值,则将数据类型更改为字符串.提交字符串的问题是服务器需要一个没有隐式转换可用的数字值.
When I bind numeric data in my view model using knockout, it displays correctly but changes the data type to string if the user changes the input tag value. The problem with submitting string is that the server expects a numeric value with no implicit conversion available.
有什么方法可以告诉敲除法来保持原始属性值的数据类型?
我的示例代码将视图模型名称与输入标签名称匹配.我使用通俗易懂的方法进行绑定,效果很好.
My example code that matches the view model names to the input tag names. I use unobtrusive knockout to do the bindings, which works fine.
// 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);
推荐答案
Here is a thread with a few different techniques to keep the value numeric: https://groups.google.com/d/topic/knockoutjs/SPrzcgddoY4/discussion
一个选择是将这种关注放入您的视图模型中,并创建一个numericObservable
代替常规的可观察对象使用.可能看起来像:
One option is to push this concern into your view model and create a numericObservable
to use instead of a normal observable. It might look like:
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;
};
示例: http://jsfiddle.net/rniemeyer/RJbdS/
另一个选择是使用自定义绑定来处理此问题.可以使用numericValue
绑定来代替使用value
绑定.它可能看起来像:
Another option is to handle this with a custom binding. Instead of using the value
binding, you can define a numericValue
binding and use it instead. It could look like:
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);
}
};
示例: http://jsfiddle.net/rniemeyer/wtZ9X/
这篇关于Knockout.js:时间输入格式和值限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!