如何在不删除图标的情况下将图标添加到绑定中?

时间:2016-07-26 18:19:57

标签: javascript html knockout.js binding

我正在尝试创建一个带下拉菜单的菜单栏,单击时会显示下拉菜单,并将图标从右箭头更改为向下箭头。但是,Knockout JS会继续删除绑定中的span标记。我怎么能绕过这个?

这是我的HTML:

<!-- Recursively traverse the nested structure -->
<ul data-bind="template: {name: 'document_index_template', foreach: children}"><l><a href="#">Document Index</a></l></ul>

<script type="text/html" id="document_index_template">
    <li class="collapsible-child" >
        <a data-bind="text: label, click: function(){isExpanded(!isExpanded())}" href="#"><span class="glyphicon glyphicon-triangle-right" ></span></a>

        <ul class="collapsible-child" data-bind='template: { name: "document_index_template", foreach: visibleChildren}'></ul>
    </li>
</script>

这是我的ViewModel:

var document_type = 'loan';
var key = 'comparison';
define(['jquery', 'knockout'], function($, ko){

    var structureRequest = getStructure();
    structureRequest.then(function(data){
        window.treeNode = new TreeNode(data);
        ko.applyBindings(window.treeNode);
    });

    function TreeNode(data){
        var self = this;

        self.key = ko.observable(data.key);
        self.label = ko.observable(data.label);
        self.children = ko.observableArray([]);

        $.each(data.children, function(index, child){
            self.children.push(new TreeNode(child));
        });

        self.isExpanded = ko.observable(false);

        self.visibleChildren = ko.computed(function(){
            if(self.isExpanded()){
                return self.children();
            }else{
                return [];
            }
        });
    }

    function getStructure() {
        var url = "../structure/api/0?document_type=" + document_type + "&key=" + key;
        return $.ajax({
            url: url,
            type: "GET",
            dataType: "json"
        });
    }
});

1 个答案:

答案 0 :(得分:1)

text数据绑定清除节点并注入文本节点。你必须将文本绑定向下移动一级:

<a data-bind="click: function(){ isExpanded(!isExpanded()) }" href="#">   
  <span data-bind="text: label"></span>
  <span class="glyphicon glyphicon-triangle-right"></span>
</a>

供参考:这是来自淘汰赛源的评论:

  

我们需要有一个孩子:一个文本节点。如果没有子节点,不止一个节点,或者它不是文本节点,我们将清除所有内容并创建单个文本节点。

https://github.com/knockout/knockout/blob/master/src/utils.js#L433