【问题标题】:Knockout custom binding descendant $data works only when the property already exists敲除自定义绑定后代 $data 仅在属性已存在时才有效
【发布时间】:2016-07-13 04:39:03
【问题描述】:

每个人。我正在阅读 Knockout js 文档here,它与控制后代绑定有关。场景是我使用 applyBindingsToDescendants 将后代元素与当前绑定上下文绑定,然后我尝试使用 $data.property_name 在后代元素中访问该绑定上下文中的属性,它仅在 property_name 已经在原始元素中时才有效binding_context,如果稍后添加,那么 $data.property_name 将不起作用,但如果我删除 $data 它将起作用,请查看此jsfiddle example。谁能告诉我为什么会这样?

html

<div data-bind="addBindingProperties: {addedProp: 'ADDED PROPERTY'}">
    <div>Existing property accessible via $data: <span data-bind="text:   $data.existingProp"></span></div>
    <div>Added property not accessible via $data: <span data-bind="text: $data.addedProp"></span></div>
    <div>Added property accessible by removing $data: <span data-bind="text: addedProp"></span></div>
</div>

javascript

ko.bindingHandlers.addBindingProperties = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        ko.utils.extend(bindingContext, valueAccessor());
        ko.applyBindingsToDescendants(bindingContext, element);
        return {controlsDescendantBindings: true};
    }
};

ko.applyBindings({
    existingProp: 'EXISTING PROPERTY'
});

结果

Existing property accessible via $data: EXISTING PROPERTY
Added property not accessible via $data:
Added property accessible by removing $data: ADDED PROPERTY

【问题讨论】:

    标签: knockout.js


    【解决方案1】:

    你的$data 在这里暗示你的根视图模型,所以这部分是错误的ko.utils.extend(bindingContext, valueAccessor()); 因为你实际上只是将它扩展到当前上下文,因此它没有附加到$data

    您可以将其扩展到根上下文,以便该属性存在于$data 中,例如:

    ko.utils.extend(bindingContext, valueAccessor());
    ko.utils.extend(bindingContext.$root, valueAccessor());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多