简体   繁体   English

.replace()表达式未在计算的可观察范围内更新

[英].replace() expression not being updated within computed observable

I have created within knockoutJS a computed observable that supports user input as well as performs text manipulation on the input. 我在kickoutJS中创建了一个可计算的可观察值,它支持用户输入以及对输入执行文本操作。

This observable is bound to input field and label. 该可观察值绑定到输入字段和标签。 The intent is to allow a user to enter a new name but I want to prevent the user from using non-alphanumeric characters. 目的是允许用户输入新名称,但我想阻止用户使用非字母数字字符。 The function works both in bindings and evaluation of the string, but the replace function does not seem to update. 该函数可在字符串的绑定和求值中使用,但是replace函数似乎没有更新。 The substring function works (limiting the text to 255 characters) but I think I have something not set exactly right in the replace. 子字符串函数有效(将文本限制为255个字符),但我认为我在替换项中未设置正确的内容。 Int eh current funciton, if an illegal character is entered the user receives the toastr alert but the replace function does not replace the character with white space. 在当前功能中,如果输入了非法字符,则用户会收到烤面包机警报,但替换功能不会将字符替换为空格。 I'd appreciate any suggestions. 我将不胜感激任何建议。

html html

<label class="reportNameTextBox" title="Click to edit report name"  data-bind="text: NameFormatted() == null || NameFormatted().trim().length == 0 ? '[ Click To Enter Name ]' : NameFormatted(), css: { 'noData': NameFormatted() == null || NameFormatted().trim().length == 0 }"></label>
            <input class="editInput" type="text" data-bind="value: NameFormatted" />

knockout 昏死

report.NameFormatted = ko.computed({
     read: function () {
           return report.Name().substring(0, 255);
           },
     write: function (value) {
           var insertedText = value;
           var Exp = /^[a-zA-Z0-9]*$/i;
           if (!insertedText.match(Exp)) {
           DisplayWarning('Attention', 'Non-alphanumeric may not be used.');
                            return report.Name(insertedText.substring(0, 255)).replace(/[^a-zA-Z 0-9]+/g, ''); ;
           }
           else {
           DisplayWarning('Success', 'yeah');
           return report.Name(insertedText.substring(0, 255));
           }
          },
    owner: this
});

I believe your problem lies on this line: 我相信您的问题出在这条线上:

return report.Name(insertedText.substring(0, 255)).replace(/[^a-zA-Z 0-9]+/g, '');

You're chaining the replace method to the wrong object ( report.Name instead of substring ) 您正在将replace方法链接到错误的对象( report.Name而不是substring

return report.Name(insertedText.substring(0, 255).replace(/[^a-zA-Z 0-9]+/g, ''));

Just move the replace method inside the bracket and it should work as expected. 只需将替换方法移到支架内即可,它应该可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM