0

我想知道如何使动态添加的嵌套对象的淘汰绑定工作。以下示例演示了我的意思,当我单击“初始化内部”按钮时,它不显示“内部值”:

<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>
4

2 回答 2

1

您应该将此对象声明为可观察对象并将其值设置为函数访问它

<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 -从对象更新视图模型不起作用

于 2012-07-20T20:31:58.910 回答
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);
});

于 2012-07-21T01:49:21.080 回答