如何将observableArray属性与另一个dom元素绑定

时间:2015-02-03 23:22:08

标签: knockout.js

请查看此示例http://jsfiddle.net/sLeh8f42/

从表格中的所有“全名”文本框到复选框列表实现“单向绑定”的最佳方法是什么?

现在,通过单击“添加”按钮,它只会添加一个带有空文本框的新行。

JS:

function Person(id, fullname) {

    return { Id: id, FullName: fullname };
}  

    var FullName = function (fullname, checked) {

            var self = this;
            self.FullName = ko.observable(fullname);
            self.Checked = ko.observable(!!checked);

            self.Checked.subscribe(function () {
                alert(self.FullName() + " is " + self.Checked());
            });
        }

    function ViewModel() {

            var self = this;
            self.PersonArray = ko.observableArray([new Person("1", "Jackie CHAN")]);

            self.Names = ko.computed(function () {
                var arr = [];
                ko.utils.arrayForEach(self.PersonArray(), function (person) {

                    arr.push(new FullName(person.FullName, false));
                });

                return arr;
            });

            self.AddPerson = function () {

                self.PersonArray.push(new Person("", ""));
            };

            self.RemovePerson = function () {

                self.PersonArray.remove(this);
            };       
        }

        ko.applyBindings(new ViewModel());  

感谢。

1 个答案:

答案 0 :(得分:0)

不要使用NamesPersonArray,而只需使用PersonArray并让人使用可观察对象。

function Person(id, fullname, checked) {
    var self = this;
    self.Id = ko.observable(id);
    self.FullName = ko.observable(fullname);
    self.Checked = ko.observable(checked);

    self.Checked.subscribe(function () {
        alert(self.FullName() + " is " + self.Checked());
    });
}  

function ViewModel() {

    var self = this;
    self.PersonArray = ko.observableArray([new Person("1", "Jackie CHAN", false)]);

    self.AddPerson = function () {

        self.PersonArray.push(new Person("", "", false));
    };

    self.RemovePerson = function () {

        self.PersonArray.remove(this);
    };       
}

ko.applyBindings(new ViewModel());
<div data-bind="foreach: PersonArray">
    <div>
        <input type="checkbox" data-bind="checked: Checked" />
        <label data-bind="text: FullName"></label>
    </div>
</div>

jsFiddle