0

我想通过单击它来选择一个简单的表格行,就像这里一样:

http://jsfiddle.net/rniemeyer/APzK8/6/

我应用了上述逻辑,但仍然没有选择任何内容,我做错了什么?

数据显示正确,只是选择不起作用。

define(['services/dataservice'], function (dataservice) {

    var self = this;
    this.Selected = ko.observable();
    var schoolyears = ko.observableArray();

    this.SelectSchoolyear = function (config) {
        self.Selected(config);
    };

    this.Selected(schoolyears()[0]);

    var vm = {
        activate: activate,
        schoolyears: schoolyears,
        title: 'Schoolyears'
        };
    return vm;

    function activate(){
        var schoolyearModels = dataservice.getSchoolyears();
        var schoolyearViewModels = [];
        for (var i = 0; i < schoolyearModels.length; i++){
            var e = schoolyearModels[i];
            var schoolyearViewModel = new SchoolyearViewModel(e.schoolyearId, e.schoolyearName, e.from, e.to, e.lastEdited, self.Selected);
            schoolyearViewModels.push(schoolyearViewModel);
        }
        return schoolyears(schoolyearViewModels);
    }
    function SchoolyearViewModel(id, schoolyearName, from, to, lastEdited, selected){
        var me = this;
        this.schoolyearId = id;
        this.schoolyearName = ko.observable(schoolyearName);
        this.from = ko.observable(from);
        this.to = ko.observable(to);
        this.lastEdited = ko.observable(lastEdited);
        this.AmISelected = ko.computed(function (){
            debugger;
            return selected() === me;
        });
    }  

});


<section id="schoolyears-view" class="view">
    <a class="btn btn-info btn-force-refresh pull-right" data-bind="click: remove" href="#"><i class="icon-remove"></i>Delete</a>

    <table class="table table-striped table-bordered table-condensed">
        <thead>
            <tr>
                <th style="width: 25%">Schoolyear name</th>
                <th style="width: 25%">From</th>
                <th style="width: 25%">To</th>
                <th style="width: 250%">Last edited</th>
            </tr>
        </thead>
        <tbody data-bind="foreach: schoolyears">
            <tr data-bind="click: $parent.SelectSchoolyear, css: { selected: AmISelected }, attr: { 'data-id': schoolyearId }" >
                <td data-bind="text: schoolyearName()"></td>
                <td data-bind="text: from()"></td>
                <td data-bind="text: to()"></td>
                <td data-bind="text: lastEdited()"></td>
            </tr>
        </tbody>
    </table>
</section>
4

1 回答 1

1

问题似乎是 Knockout 正在寻找对象上的removeSelectSchoolyear方法vm,但它们不存在。他们只在this对象上。

这是一个解决方案(请注意,您仍然需要一个实现remove):

var vm = {
   activate: activate,
   schoolyears: schoolyears,
   title: 'Schoolyears',
   SelectSchoolyear: self.SelectSchoolyear,
   remove: function () {}
};

这假设在activate某处被调用。

vm.activate();

我在这里做了一个工作的JSFiddle

注意:要查看绑定错误(就像我提到的那样),只需使用浏览器的开发者控制台(Knockout 会抛出异常)。

于 2013-05-05T16:29:24.463 回答