我正在使用KnockoutJS创建一个应用程序,我需要将<textarea>
中的行数(行数)限制为8,将每行的字符数限制为25.我面临以下问题:
这是我的代码:
HTML
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!-- This is a *view* - HTML markup that defines the appearance of your UI -->
<textarea data-limit-rows="true" cols="30" rows="9" data-bind="event: {keyup:check}"></textarea>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-debug.js"></script>
<script src="js/script.js" charset="utf-8"></script>
</body>
</html>
JS
function AppViewModel() {
this.check= function(d,e) {
var maxLength = 25;
var text = $(e.currentTarget).val(),
lines = text.split(/(\r\n|\n|\r)/gm),
//maxRows = parseInt($(e.currentTarget).attr("rows"));
maxRows=8;
for (var i = 0; i < lines.length; i++) {
if (lines[i].length > maxLength) {
lines[i] = lines[i].substring(0, maxLength);
}
}
};
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
先谢谢
答案 0 :(得分:1)
我建议您使用ko.computed
read
和write
功能。使用textInput
绑定对此可观察数据进行数据绑定。
write
将文本输入存储在内部支持字段中。 read
转换并限制字符串以满足您的要求。
请注意,此处notify: always
扩展程序非常重要。当新的 raw 输入生成相同的计算输入时,knockout将不会触发更新,并且您的textarea将不会被清除。通过使用notify: always
,您可以告诉knockout每次都重置textarea,即使它是相同的值。
function AppViewModel() {
var MAX_LINES = 4;
var MAX_LENGTH = 5;
var rawValue = ko.observable("");
this.value = ko.computed({
read: function() {
return rawValue()
.split("\n")
.reduce(function(lines, line) {
if (line.length === 0) {
lines.push("");
}
while(line.length) {
lines.push(line.slice(0, MAX_LENGTH));
line = line.slice(MAX_LENGTH, line.length);
}
return lines;
}, [])
.slice(0, MAX_LINES)
.join("\n");
},
write: rawValue
}).extend({"notify": "always"});
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<textarea cols="25" rows="9" data-bind="textInput: value"
style="font-family: monospace"></textarea>
&#13;