xyz*_*xyz 14 html javascript knockout.js
我的淘汰视图模型中有一个可观察的名称字段.现在我想限制该字段中的字符数,如果它超过一定数量.
好像名字="约翰·史密斯",我有6个字符的限制,然后
显示"john s ..."
Jos*_*iel 20
另一种可重用的解决方案是创建一个自定义绑定,显示文本的剪裁版本.
这允许基础值保持不受影响,但修剪文本以用于显示目的.这对于消息预览或将数据拟合到网格列中非常有用.
示例绑定:
ko.bindingHandlers.trimLengthText = {};
ko.bindingHandlers.trimText = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var trimmedText = ko.computed(function () {
var untrimmedText = ko.utils.unwrapObservable(valueAccessor());
var defaultMaxLength = 20;
var minLength = 5;
var maxLength = ko.utils.unwrapObservable(allBindingsAccessor().trimTextLength) || defaultMaxLength;
if (maxLength < minLength) maxLength = minLength;
var text = untrimmedText.length > maxLength ? untrimmedText.substring(0, maxLength - 1) + '...' : untrimmedText;
return text;
});
ko.applyBindingsToNode(element, {
text: trimmedText
}, viewModel);
return {
controlsDescendantBindings: true
};
}
};
Run Code Online (Sandbox Code Playgroud)
像这样使用它:
<div data-bind="trimText: myText1"></div>
Run Code Online (Sandbox Code Playgroud)
要么...
<div data-bind="trimText: myText1, trimTextLength: 10"></div>
Run Code Online (Sandbox Code Playgroud)
Chr*_*xon 18
<span data-bind="text: (name.length > 6 ? name().substring(0, 5) + '...' : name)"></span>
Run Code Online (Sandbox Code Playgroud)
或者,您可以在ViewModel中创建计算的observable,例如:
var self = this;
this.shortName = ko.computed(function() {
return (self.name.length > 6 ? self.name().substring(0, 5) + '...' : self.name);
});
Run Code Online (Sandbox Code Playgroud)
然后:
<span data-bind="text: shortName"></span>
Run Code Online (Sandbox Code Playgroud)
如果您有一个具有最大长度的字段,Chris Dixon的解决方案是完美的.但是如果你不得不多次重复这个操作就会变得很麻烦.那时你应该编写一个自定义的可观察扩展器,如下所示:
ko.extenders.maxLength = function(target, maxLength) {
//create a writeable computed observable to intercept writes to our observable
var result = ko.computed({
read: target, //always return the original observables value
write: function(newValue) {
var current = target(),
valueToWrite = newValue ? newValue.substring(0, Math.min(newValue.length, maxLength)) : null;
//only write if it changed
if (valueToWrite !== current) {
target(valueToWrite);
} else {
//if the rounded value is the same, but a different value was written, force a notification for the current field
if (newValue !== current) {
target.notifySubscribers(valueToWrite);
}
}
}
});
//initialize with current value to make sure it is rounded appropriately
result(target());
//return the new computed observable
return result;
};
Run Code Online (Sandbox Code Playgroud)
然后,您可以在任何可观察对象上使用它,并且可以为它们中的任何一个指定不同的最大长度.这消除了HTML(解决方案1)中的混乱,以及编写计算的可观察量(解决方案2)的必要性.您只需按以下方式定义您的observable:
this.shortName = ko.observable().extend({ maxLength: 25 });
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19715 次 |
| 最近记录: |