如何在Knockout中重新绑定具有不可观察对象的元素?

时间:2013-01-09 14:14:51

标签: javascript knockout.js

如何在Knockout中重新绑定具有不可观察对象的元素?假设我有

<ul data-bind="attr:{ }, foreach: items"><li><a rel="external" data-bind="attr: { href: full }" ><img data-bind="attr: { src: thumb, alt: caption }" /></a></li></ul>

我可以正确绑定,

{
"items":[
                    { "full": "Content\/ImageGallery\/full\/20120502_180612_Josh_Wave_Pint.jpg", "thumb": "content\/imagegallery\/thumb\/20120502_180612_Josh_Wave_Pint.jpg", "caption": "Picture" },
                    {"full":"Content\/ImageGallery\/full\/20130109_173902.jpg","thumb":"content\/imagegallery\/thumb\/20130109_173902.jpg","caption":"Picture"},
                    { "full": "Content\/ImageGallery\/full\/20130107_193641.jpg", "thumb": "content\/imagegallery\/thumb\/20130107_193641.jpg", "caption": "Picture" }
                    ] }

但是如何重新绑定呢?这不起作用,

ko.applyBindings(updatedJsonObject, $element[0]);

1 个答案:

答案 0 :(得分:2)

如果你不能使你的数组​​成为observableArray,那么你的主要选择是将整个结构放在一个observable中:

var myStructure = ko.observable();

//update myStructure with new data
myStructure({[...]});

然后,你会像它一样绑定它:

<div data-bind="with: myStructure">
    <ul data-bind="attr:{ }, foreach: items"><li><a rel="external" data-bind="attr: { href: full }" ><img data-bind="attr: { src: thumb, alt: caption }" /></a></li></ul>
</div>

现在,即使数组不可观察,每当您更新myStructure(可观察)时,整个部分都将被重新渲染。