将KnockoutJS与分离的节点一起使用 [英] Using KnockoutJS with detached nodes

查看:93
本文介绍了将KnockoutJS与分离的节点一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要做的是使用jQuery的detach方法分离一些节点,更新我的ViewModel,重新连接节点,并更新值。

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.

这可能吗?

这是我的完整小提琴为...射击。基本上,我希望能够从左到右,点击分离,更新和附加,并在文本框中有新的值。

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.

更新

根据RP的回答,假设这适合您的用例,最好的选择是附加它们到dom 隐藏,更新您的viewmodel,然后显示您的节点。这样的东西适合我:

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

以下是完整代码:

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>


推荐答案

评估单个<$ c中的绑定$ c> data-bind 包装在一个计算的observable中,当它被重新评估时会自行处理,并且识别出它不是当前文档的一部分。

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.

这篇关于将KnockoutJS与分离的节点一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆