如何防止knockout.js在应用绑定时删除FireFox预填充的表单字段值

时间:2015-04-25 16:42:09

标签: javascript html forms firefox knockout.js

FireFox在加载页面(例如用户名等)后在输入框中预填充某些表单值。

如果我将Knockout.js绑定应用于预填充表单,则在应用绑定时,Knockout将清除输入字段(导致短暂闪烁)。

有没有办法保留预先填充的值而不是删除它们?

   var UserModel = function() {
        this.username = ko.observable();
        this.password = ko.observable();
        this.passwordRepeat = ko.observable();
        ....
   }
   ....
   domReady(function() {
      //values prefilled by FireFox in input box bound to username are 
      //erased after applyBindings is executed
      ko.applyBindings(new UserModel());
   });

1 个答案:

答案 0 :(得分:2)

您可以使用自定义绑定,或覆盖/扩展textInput和/或值绑定,以使用DOM中的值初始化observable。

// w/ custom binding
ko.bindingHandlers.prefilledText = {
    init: function(el, valueAccessor) {
        // set initial value
        var initVal = $(el).val()
        valueAccessor()(initVal)

        // apply normal textInput binding
        ko.applyBindingsToNode(el, {
            textInput: valueAccessor()
        })
    }
}

// w/ extended textInput binding

// save reference to initial binding
var _textInputBinding = ko.bindingHandlers.textInput

ko.bindingHandlers.textInput = {
    init: function(el, valueAccessor) {
        // set initial value, same as before
        var initVal = $(el).val()
        valueAccessor()(initVal)

        // pass on to the regular textInput binding
        _textInputBinding.init.apply(this, arguments)
    },
    // don't forget the update function either!
    update: _textInputBinding.update
}

fiddle