【问题标题】:Bind to a selected item of the foreach binding with knockout.js使用 knockout.js 绑定到 foreach 绑定的选定项
【发布时间】:2012-07-14 19:16:41
【问题描述】:

我正在使用 knockout.js 和 ko.mapping 插件将 json 对象列表绑定到 html 网格。让我们将每个项目称为卡片(下面的简化示例)

{
    "card": [
        {
            "Id": "cards/1",
            "category": "Demo",
            "title": "Card 1",
            "description": "bla bla",
            "picture": "demo1.jpg ",
            "madeBy": "user/1"
        },
        {
            "Id": "cards/2",
            "category": "Demo",
            "title": "Card 2",
            "description": "bla bla",
            "picture": "demo2.jpg",
            "madeBy": "user/2"
        }
    ]
}

我像这样绑定每个元素:

 <div data-bind="foreach: card">
    <span data-bind="text:title"></span>
    <a data-bind='click: show'><img data-bind="attr:{src: picture}" /></a>
</div>

当用户点击一张卡片时,我想在不同的 div 中(在 foreach 之外)显示所选卡片,其中包含来自所选 json 对象的更多属性

我应该将谁绑定到视图模型中的一张选定卡片?

我正在尝试类似的东西(但没有得到任何数据):

<h1 data-bind="text: $data.title"> </h1>

【问题讨论】:

    标签: knockout.js knockout-mapping-plugin


    【解决方案1】:

    您将希望通过在持有卡片的 ViewModel 上跟踪选定的卡片来执行此操作。 Here is a fiddle 简单地证明了这一点。这是修改后的 HTML 和 JS(为了演示的目的,这已被简化,我没有使用映射,但你明白了):

    HTML:

    <div data-bind="foreach: cards">
        <span data-bind="text:title"></span>
        <a data-bind='click: $parent.selectedCard'>ImagePlaceholder</a>
        </br>
    </div>
    
    <div data-bind="with: selectedCard">
        <h1 data-bind="text: title"></h1>
        <span data-bind="text: description"></span>
    </div>
    

    JS

    var ViewModel = function(cards) {
        this.cards = ko.observableArray(
            ko.utils.arrayMap(cards, function(c) {return new Card(c);})
        );
        this.selectedCard = ko.observable();
    };
    

    注意click直接设置选择的卡,不需要使用包装器“显示”功能。由于 observables 函数,我们可以跳过这一步(当然,除非你需要在 show 函数中做更多的事情)。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-18
    • 2016-08-25
    • 2021-07-04
    • 2012-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多