1

对于淘汰赛,如果发生重新绑定,为什么 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。见德克的回答。

4

3 回答 3

2

with如果绑定到可观察对象并且您更改了可观察对象,则可观察对象上的A始终会重建 HTML。就像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());
});
于 2013-09-08T17:20:40.707 回答
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/

于 2013-09-08T16:27:54.543 回答
0

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

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

$(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");  
});
于 2013-09-08T16:40:55.607 回答