Knockout重新绑定会重置HTML

时间:2013-09-08 16:17:44

标签: javascript knockout.js

使用knockout,如果发生重新绑定,为什么HTML会重置为初始状态?请查看以下代码(http://jsfiddle.net/mgs_jsfiddle/KNnmC/

<div data-bind="with: person">
   <p>person <input type="text" data-bind="value: firstName"/></p>
</div>

<div>
    <a href="#" data-bind="click: moveNext">moveNext</a>
</div>

$(function() {
    function ViewModel() {
        var self = this;
        self.person = ko.observable({ firstName: "first"});
        self.moveNext = function() {
            self.person({ firstName: "second"});
        };
    };
    ko.applyBindings(new ViewModel());
    $("input").css("background-color", "#ffff00");
});

如果单击锚点,则输入元素将丢失其背景颜色。为什么不只是改变了价值?

更新:我扩展了jsFiddle以显示with负责重新生成HTML。见德克的答案。

3 个答案:

答案 0 :(得分:2)

如果一个observable绑定到一个observable并且你改变了observable,它就会重建HTML with。就像添加或删除元素时foreach一样。我不知道你用jQuery改变背景颜色的具体原因,但我很确定有更好的“淘汰”方式。

例如:

http://jsfiddle.net/KNnmC/66/

<div data-bind="with: person">
   <p>person <input type="text" data-bind="value: firstName, style: { background: hasBeard ? 'yellow' : 'red' }"/></p>
</div> 
<div>
    <a href="#" data-bind="click: moveNext">moveNext</a>
</div>

$(function() {
    function ViewModel() {
        var self = this;
        self.person = ko.observable({ firstName: "first", hasBeard: true});
        self.moveNext = function() {
            self.person({ firstName: "second", hasBeard: false});
        };
    };
    ko.applyBindings(new ViewModel());
});

答案 1 :(得分:0)

ko.applyBindings(new ViewModel());

之前移动背景声明

<强> HTML

    
<div data-bind="with: person">
   <p>person <input type="text" data-bind="value: firstName"/></p>
</div>

<div>
    <a href="#" data-bind="click: moveNext">moveNext</a>
</div>

<强>的JavaScript

$(function() {       
    function ViewModel() {
        var self = this;
        self.person = ko.observable({ firstName: "first"});
        self.moveNext = function() {
            self.person({ firstName: "second"});
        };
    };
    $("input").css("background-color", "#ffff00");
    ko.applyBindings(new ViewModel());    
});

http://jsfiddle.net/KNnmC/64/

答案 2 :(得分:0)

我认为这种情况正在发生,因为firstName不可观察,并且您基本上要求Knockout每次都在with内重建模板。

相反,定义一个类似于此的模型:

$(function() {       
    function ViewModel() {
        var self = this;
        self.person = { 
            firstName: ko.observable("first")
        }
        self.moveNext = function() {
            self.person.firstName("second");
        };
    };
    ko.applyBindings(new ViewModel());
    $("input").css("background-color", "#ffff00");  
});