JavaScript事件,不更新knockout observable / model值

时间:2016-08-23 21:03:54

标签: javascript asp.net-mvc knockout.js

我有一个文本字段,它与Keyup& amp;改变事件,修剪字段长度。

function trimField(data, event) {
    var obj = event.target;
    var maxlength = parseInt(obj.getAttribute('maxlength'), 10);
    obj.value = obj.value.substring(0, maxlength);
    obj.focus();
    return true;
}

修剪功能,

ffmpeg  -re -i input.m3u8 -f flv - 2>/dev/null|pv -a >/dev/null

如果我输入“123456”,则在UI上显示“12345”,但模型显示为“123456”。

如何在keyup事件后更新模型?

3 个答案:

答案 0 :(得分:1)

您没有更新绑定到元素的可观察变量。最好将它作为一个可观察的扩展,以便它可以根据你的最大长度在任何地方使用,并确保它遵循你的规则获得初始值。

示例:https://jsfiddle.net/kyr6w2x3/55/

HTML:

 <input data-bind='textInput: zipCode' />
 <div>
   zip code in Model:<span data-bind="text:zipCode"></span>
 </div> 

JS:

   function AppViewModel(input) {
    this.zipCode = ko.observable(input).extend({ maxLength:5});
    this.phone = ko.observable(input).extend({ maxLength:11});
   }



 ko.extenders.maxLenght = function(target, characters) {
     //you can use this to show an error message on view 
    // target.validationMessage = ko.observable();

    //define a function to do validation for maxLength
    function validate(newValue) {

    var maxlength = parseInt(characters, 10);
     if(newValue){
      target(newValue.substring(0, maxlength) ); 
     }

    }

    //initial validation
    validate(target());

    //validate whenever the value changes
    target.subscribe(validate);

    //return the original observable
    return target;
};

ko.applyBindings(new AppViewModel("12345678910"));

答案 1 :(得分:0)

将maxlength从5更改为6:

@Html.TextBoxFor(m => m.zipCode, new {data_bind = "textInput: zipcode, event: { keyup: trimField, change: trimField }", maxlength = "6"})

答案 2 :(得分:0)

停止修改DOM。这是Knockout的工作。您只需修改数据项,Knockout将确保UI正确。

function trimField(data, event) {
    var obj = event.target;
    var maxlength = parseInt(obj.getAttribute('maxlength'), 10);
    data.zipcode(data.zipcode().substr(0, maxlength));
    return true;
}