Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

javascript - Using KnockoutJS with detached nodes

What I'm looking to do is detach some nodes using jQuery's detach method, update my ViewModel, attach my nodes back, and have the values be updated.

Is this possible?

Here's a full fiddle of what I'm shooting for. Basically, I'd like to be able to go from left to right, click detach, update, and attach and have fresh values in the textboxes.


UPDATE

Based on RP's answer, the best bet, assuming this fits your use case, is to attach them to the dom hidden, update your viewmodel, and then show your nodes. Something like this works for me:

$("#updateAndAttach").click(function () {
    var junk = $("<div />").css("display", "none");
    junk.append(nodes);
    $("#home").append(junk);

    vm.a("AAA");
    vm.b("BBB");

    $(nodes).unwrap();
});

END UPDATE


Here's the full code:

JavaScript

$(function () {

    function ViewModel() {
        this.a = ko.observable("a");
        this.b = ko.observable("b");
    }

    var vm = new ViewModel();

    ko.applyBindings(vm, document.getElementById("home"));

    var nodes = null;

    $("#detach").click(function () {
        nodes = $("#home").children().detach();
    });

    $("#attach").click(function () {
        $("#home").append(nodes);
    });

    $("#update").click(function () {
        vm.a("AAA");
        vm.b("BBB");
    });
})();

HTML:

<div id="home">
    <input type="text" data-bind="value: a" />
    <input type="text" data-bind="value: b" />
</div>

<button id="detach">Detach</button>
<button id="update">Update</button>
<button id="attach">Attach</button>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The evaluation of the bindings in a single data-bind are wrapped in a computed observable that will dispose of itself when it is re-evaluated and recognizes that it is not part of the current document.

So, there is not a simple workaround that would allow you to do what you are trying. You could certainly hide the elements while updates are being made and then unhide them.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...