未选中通过knockoutjs绑定的单击表行

时间:2013-05-04 22:44:28

标签: knockout.js

我想通过单击它来选择一个简单的表行:

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>

1 个答案:

答案 0 :(得分:1)

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

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

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

这假定activate在某个地方被调用。

vm.activate();

我做了一个有效的JSFiddle here

注意:要查看绑定错误(如我提到的那些),只需使用浏览器的开发人员控制台(Knockout将抛出异常)。