【问题标题】:Nested ForEach with afterRender callbacks in knockout.js在 knockout.js 中使用 afterRender 回调嵌套 ForEach
【发布时间】:2013-09-04 06:55:51
【问题描述】:

我想要什么:从我的嵌套 foreach 访问自定义 afterRender。

我有什么:

我正在构建一个可折叠的播客列表,每个播客都有多个类别。我目前拥有的是使用 foreach 生成的播客列表,其中的类别元素是使用另一个 foreach 生成的。

<div id="content-programs">
        <!-- content -->
        <div data-role="collapsible-set" data-bind="foreach: { data: entries }">
            <div class="entry" data-role="collapsible" data-collapsed="false">
                <h3 data-bind="text: title"></h3>

                <b>Author:</b> <span data-bind="text: author"></span><p>
                <b>Published:</b> <span data-bind="text: publishedDate"></span><p>

                <p>
                    <span data-bind="text: contentSnippet"></span>
                    <a data-bind="attr: {href: link}" >Full Story</a>               
                </p>

                <b>Categories:</b>
                <div data-bind="foreach: categories">
                    <span data-bind="text: $data"></span>
                </div>          

            </div>
        </div>
    </div>

我的要求实际上很简单,我只想用逗号分隔类别。我可以对数据或类似的东西进行此操作,但我也在探索淘汰赛,并对它可以提供什么感兴趣。

这是我尝试过的:

        feed = ko.mapping.fromJS(response.responseData.feed);
        ko.applyBindings
        (
            {
                entries:        feed.entries,                       
                arCategories:   
                function(categories, data)
                {
                    alert(data);
                }                   
            }
        );

HTML

<b>Categories:</b>
    <div data-bind="foreach: {data: categories, afterRender: arCategories}">
        <span data-bind="text: $data"></span>
    </div>

【问题讨论】:

    标签: javascript knockout.js foreach


    【解决方案1】:

    因为您在 foreach 的上下文中,所以您需要使用 $parent 来访问您的 arCategories 方法,该方法被声明为“升级”。

    <div data-bind="foreach: {data: categories, afterRender: $parent.arCategories}">
       <span data-bind="text: $data"></span>
    </div>
    

    演示JSFiddle.

    有关详细信息,另请参阅文档中的 Note 2: Using $index, $parent, and other context propertiesBinding context 页面。

    旁注:

    如果你只想要一个逗号分隔的列表,你可以使用array.join() method

    <div data-bind="text: categories.join()"></div> 
    

    演示JSFiddle.

    【讨论】:

    • 确认这个工作,并感谢文档链接。我觉得我已经浏览了那个页面,但是标记和 js 之间的脱节使得很难填补空白。谢谢!
    • 另外,感谢 .join 评论。因为我已经映射了我的数组,所以我不得不使用 categories().join(),但它工作得很好。
    猜你喜欢
    • 2012-06-10
    • 2013-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-25
    • 2012-02-16
    • 2014-02-25
    • 1970-01-01
    相关资源
    最近更新 更多