带有扩展/折叠的敲除js foreach绑定 [英] Knockout js foreach binding with expand/collapse

查看:78
本文介绍了带有扩展/折叠的敲除js foreach绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了一些教程,并尝试了几个小时才能使其正常工作.我的目标是拥有多个链接,这些链接在单击时会扩展/折叠.到目前为止,我有以下内容:

I've read a couple tutorials and tried for a couple hours trying to get this to work. My goal is to have multiple links that expand/collapse when they are clicked on. So far I have the following:

HTML:

<ul data-bind="foreach: items">
    <a href="#" data-bind="click: $parent.toggle, text: $parent.linkLabel"></a>        
    <button data-bind="text: name, click: $parent.clickTask"></button>
    <div data-bind="visible: $parent.expanded">
        <input data-bind="value: name"></input>
    </div>
</ul>

JS:

var viewModel = function() {
    var self = this;

    self.items = [{"name":"bruce","id":1},{"name":"greg","id":2}]

    self.expanded = ko.observable(false);

    self.linkLabel = ko.computed(function () {
        return self.expanded() ? "collapse" : "expand";
    }, self);      

    self.toggle = function (item) {
        self.expanded(!self.expanded());
    };
};

ko.applyBindings(new viewModel());

JSFiddle Here

我现在知道我在父级上具有展开状态,这就是为什么一切都展开/折叠的原因.我将如何让每个项目跟踪其自身的展开/拼贴状态?

I understand right now I have the expanded state on the parent which is why everything expands/collapses. How would I get each item to keep track of its own expand/collage state?

推荐答案

好吧,您通过引用parent来为所有可观察对象创建一个single dependency,这是这里的问题.

well you are creating a single dependency for all observable's by referring parent which is the issue here .

因此,您需要对每个列表项具有独立的依赖性,并使 $data的使用,它引用当前上下文. 所以这里的技巧是为每个列表项创建一个实例

So you need to have independent dependency for each list item and make use of $data which refers current context . So trick here is creating a instance for each listitem

视图:

<ul data-bind="foreach: items"> <a href="#" data-bind="click: toggle, text:linkLabel"></a> 
    <button data-bind="text:name"></button>
    <div data-bind="visible:expanded">
        <input data-bind="value:name"></input>
    </div>
</ul>

viewModel:

function Sample(item) {
    var self = this;
    self.name = ko.observable(item.name);
    self.id = ko.observable(item.id);
    self.expanded = ko.observable(false);
    self.toggle = function (item) {
        self.expanded(!self.expanded());
    };
    self.linkLabel = ko.computed(function () {
        return self.expanded() ? "collapse" : "expand";
    }, self);
}

var viewModel = function () {
    var self = this;

    var json = [{
        "name": "bruce",
        "id": 1
    }, {
        "name": "greg",
        "id": 2
    }]

    var data = ko.utils.arrayMap(json, function (item) {
        return new Sample(item); // making things independent here 
    });
    self.items = ko.observableArray(data);
};

ko.applyBindings(new viewModel());

此处

working sample up here

这篇关于带有扩展/折叠的敲除js foreach绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆