jquery数据表的自定义ko绑定

时间:2016-05-15 07:27:38

标签: javascript jquery knockout.js

我在knockout.js中使用了jquery dataTable。我正在使用remove link从函数生成数据行。它将删除行表格以及形成可观察数组。删除链接可以工作一次并从表中删除行但是当我试图删除另一个时,他们不会删除它。

您可以在此处查看http://jsfiddle.net/zongweil/PLUKv/1/

$(document).ready(function () {

/* Custom binding */
ko.bindingHandlers.dataTable = {
    init: function (element, valueAccessor) {
        var binding = ko.utils.unwrapObservable(valueAccessor());

        // If the binding is an object with an options field,
        // initialise the dataTable with those options. 
        if (binding.options) {
            $(element).dataTable(binding.options);
        }
    },
    update: function (element, valueAccessor) {
        var binding = ko.utils.unwrapObservable(valueAccessor());

        // If the binding isn't an object, turn it into one. 
        if (!binding.data) {
            binding = {
                data: valueAccessor()
            };
        }

        // Clear table
        $(element).dataTable().fnClearTable();

        // Rebuild table from data source specified in binding
        $(element).dataTable().fnAddData(binding.data());
    }
};


/* Object code */
function GroupMember(id, name, isGroupLeader) {
    var self = this;
    self.id = id;
    self.name = name;
    self.isGroupLeader = ko.observable(isGroupLeader);

    self.link = ko.computed(function () {
        return "/#user/" + self.id;
    });

    self.nameWithLink = ko.computed(function () {
        return '<a href="' + self.link() + '">' + self.name + '</a>';
    });

    self.actions = ko.computed(function () {
        return '<a class="btn btn-danger" data-bind="click: function() {removeMember(' + self.id + ')}">' + '<i class="icon-minus-sign"></i>' + '</a>';
    });
}

/* View model */
var groupViewModel = {
    groupMembers: ko.observableArray([
    new GroupMember("1", "Abe", true),
    new GroupMember("2", "Bob", false),
    new GroupMember("3", "Bill", false)])
};

groupViewModel.membersTable = ko.computed(function () {
    var self = this;

    var final_array = new Array();
    for (var i = 0; i < self.groupMembers().length; i++) {
        var row_array = new Array();
        row_array[0] = self.groupMembers()[i].nameWithLink();
        row_array[1] = self.groupMembers()[i].actions();
        final_array.push(row_array);
    }

    return final_array;
}, groupViewModel);

groupViewModel.removeMember = function (id) {
    var self = this;

    self.groupMembers.remove(function (groupMember) {
        return groupMember.id == id;
    });
};

ko.applyBindings(groupViewModel);

});

1 个答案:

答案 0 :(得分:0)

当您在自定义绑定的fnClearTable功能中调用update时,您可以清除淘宝网背后的部分DOM。

然后通过调用fnAddData添加新的DOM元素。

您的按钮使用click绑定。要使click绑定工作,必须applyBindings

如果您希望继续使用dataTableclick绑定来使用DOM,则每次进行更改时都必须手动应用绑定。在您的init方法中,让淘汰赛知道您正在处理后代绑定:

return { controlsDescendantBindings: true };

update方法中,手动应用绑定:

ko.applyBindingsToDescendants(viewModel, element);

这可确保您的click绑定再次有效。

以下是添加此代码的示例:http://jsfiddle.net/5t15rhyq/