如何使knockout绑定工作动态添加嵌套对象?

时间:2012-07-20 19:14:37

标签: knockout.js knockout-mapping-plugin

我想知道如何为动态添加的嵌套对象制作敲除绑定工作。以下示例阐述了我的意思,当我点击“Init inner”按钮时,它没有显示“内部值”:

<div data-bind="with: InnerObj">
    <div data-bind="text: Pr"></div>
</div>

<button data-bind="click: initInner">Init inner</button>

<script type="text/javascript" language="javascript">
var obj = { 
   InnerObj: null,
   initInner: function () { 
         this.InnerObj = { Pr: "inner value" };
   }
 }

$(function () {        
    ko.applyBindings(ko.mapping.fromJS(obj));
});    

</script>

2 个答案:

答案 0 :(得分:1)

您应该将此对象声明为observable,并将其值设置为函数

<button data-bind="click: initInner">Init inner</button>
<div data-bind="with: InnerObj">
   <span data-bind="text: Pr"/>
</div>

<script type="text/javascript" language="javascript">
var obj = { 
   InnerObj:  ko.observable(),
   initInner: function () {   
      this.InnerObj({'Pr':ko.observable('Inner value')});
   }
}


$(function () {        
    ko.applyBindings(obj);
});    

</script>

关键点:1 - InnerObj:ko.observable()            2 - this.InnerObj({'Pr':ko.observable('Inner value')});

参考:http://knockoutjs.com/documentation/observables.html - Updating view model from object not working

答案 1 :(得分:0)

这是@Victor Eloy提出的一个略微修改的例子。在obj是从服务器获取的纯模型中,没有任何可观察对象。诀窍是将它映射到ko.observable(null),遗憾的是KO映射默认不会这样做。

<button data-bind="click: initInner">Init inner</button>

<div data-bind="with: InnerObj"> 
    <div data-bind="text: Pr"></div>
</div>

<script type="text/javascript" language="javascript">

var obj = {
    // This case works too: InnerObj: { Pr: "init value"},
    InnerObj: null,

    initInner: function () {
        this.InnerObj({ Pr: ko.observable("new value") });
    }
};

var mapping = {
    'InnerObj': {
        update: function (options) {
            return (options.data == null) ? null : ko.observable(options.data);
        }
    }
};

$(function () {
    var viewModel = ko.mapping.fromJS(obj, mapping);
    ko.applyBindings(viewModel);
});