无法使用Knockout从集合绑定视图模型

时间:2013-10-14 11:44:55

标签: jquery knockout.js

我想将视图模型项绑定到集合中HTML的一部分,该集合绑定到页面中的另一个HTML。
这是我的示例HTML和JS代码:

<div>
<div style="width: 200px; float: left;" class="roundedBorder">
    <fieldset id="fieldsetCategory">
        <legend>Category</legend>
        <table>
            <thead>
                <tr>
                    <th>Category Name</th>    
                </tr>    
            </thead>
            <tbody data-bind="foreach: categories">
                <tr data-bind="click: onCategoryClick.bind($data, $parent)">
                    <td data-bind="text: name"></td>
                </tr>
            </tbody>
        </table>
    </fieldset>
</div>
<div id="divCategoryData" style="width: 200px; float: right;" class="roundedBorder">
    <fieldset id="fieldsetCategoryInfo">
        <legend>Category Information</legend>
        <table>
            <tr>
                <td>Catgory Name:</td>
                <td>
                    <strong data-bind="text: name"></strong>
                </td>
            </tr>
            <tr>
                <td>Catgory Address:</td>
                <td>
                    <strong data-bind="text: address"></strong>
                </td>
            </tr>
        </table>
    </fieldset>
</div>

<script type="text/javascript">
    function CategoryModel(name, address) {
        var self = this;
        this.name = name;
        this.address = address;
    }

    function CategoryViewModel() {
        var self = this;
        self.categories = [
            new CategoryModel("Category 1", "Delhi"),
            new CategoryModel("Category 2", "Gurgaon"),
            new CategoryModel("Category 3", "Noida"),
            new CategoryModel("Category 4", "Ghaziabad")
        ];
    }

    self.onCategoryClick = function () {
        var model = this;
        alert(model.name + " " + model.address);
        ko.applyBindings(model, "divCategoryData");

    };

    $(document).ready(function() {
        ko.applyBindings(new CategoryViewModel());
        ko.applyBindings(new CategoryModel(), "divCategoryData");
    });

</script>

我想将CategoryModel对象绑定到“divCategoryData”html部分。如您所见,模型正在传递给行事件的单击。但是,我无法显示类别名称和从列表中选择地址。
有人可以指导我“self.onCategoryClick”事件的代码片段吗?

1 个答案:

答案 0 :(得分:1)

在你的情况下,我不会尝试在每次选择更改时重新绑定div。

我建议创建一个包含所选类别的selectedCategory observable。

function CategoryModel(name, address) {
    var self = this;
    this.name = name;
    this.address = address;
}

function CategoryViewModel() {
    var self = this;
    self.categories = [
    new CategoryModel("Category 1", "Delhi"),
    new CategoryModel("Category 2", "Gurgaon"),
    new CategoryModel("Category 3", "Noida"),
    new CategoryModel("Category 4", "Ghaziabad")];

    self.selectedCategory = ko.observable();

    self.onCategoryClick = function (model) {
        //alert(model.name + " " + model.address);
        self.selectedCategory(model);

    };
}

ko.applyBindings(new CategoryViewModel());

请参阅this fiddle了解演示

我希望它有所帮助。