4

我正在使用 knockout.js 来添加和删除表单中的字段。到目前为止它工作正常,但是我需要一个 datepicker 选项,所以我使用了 jQuery 的 UI datepicker。这有效,但仅适用于第一个日期选择器,不适用于其他任何地方。因此,每当我单击“添加”时,我都会得到新字段,但没有日期选择器。

我用谷歌搜索并搜索了StackExchange,但没​​有找到复制字段的解决方案。

HTML

<table data-bind='visible: beschikkingen().length > 0'>
            <thead>
                <tr>
                    <th>Beschikkingsdatum</th>
                    <th>Beschikkingsnr</th>
                    <th />
                </tr>
            </thead>
            <tbody data-bind='foreach: beschikkingen'>
                <tr>
                    <td><input name="beschikkingsdatum[]" type="text" class="beschikkingsdatum" value="" data-bind='value: beschikkingsdatum, uniqueName: true' /> </td>
                    <td><input class='required number' data-bind='value: beschikkingsnummer, uniqueName: true' /></td>
                    <td><a href='#' data-bind='click: $root.removebeschikking'>Delete</a></td>
                </tr>
            </tbody>
        </table>

淘汰赛.JS

var beschikkingModel = function(beschikkingen) {
    var self = this;
    self.beschikkingen = ko.observableArray(beschikkingen);

    self.addbeschikking = function() {
        self.beschikkingen.push({
            beschikkingsdatum: "",
            beschikkingsnummer: ""
        });
    };

    self.removebeschikking = function(beschikking) {
        self.beschikkingen.remove(beschikking);
    };

    self.save = function(form) {
        alert("Could now transmit to server: " + ko.utils.stringifyJson(self.beschikkingen));
        // To actually transmit to server as a regular form post, write this: ko.utils.postJson($("form")[0], self.beschikkingen);
    };
};

var viewModel = new beschikkingModel([
    {
        beschikkingsdatum: "",
        beschikkingsnummer: ""
    }
]);
ko.applyBindings(viewModel);

// Activate jQuery Validation
$("form").validate({ submitHandler: viewModel.save });
//]]>  

日期选择器

$(window).load(function(){
$('.beschikkingsdatum').datepicker({
    dateFormat: 'dd-mm-yy',
    constrainInput: false
});
});
4

1 回答 1

11

使用自定义绑定处理程序可以解决您的问题:

ko.bindingHandlers.datepicker = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        var options = allBindingsAccessor().datepickerOptions || {};
        $(element).datepicker(options);

        //handle the field changing
        ko.utils.registerEventHandler(element, "change", function () {
            var observable = valueAccessor();
            observable($(element).datepicker("getDate"));
        });

        //handle disposal (if KO removes by the template binding)
        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            $(element).datepicker("destroy");
        });
    }
};

在 HTML 中:

<input data-bind='datepicker: beschikkingsdatum' />

这是工作小提琴:http: //jsfiddle.net/QUxyy/

于 2012-11-29T16:31:28.137 回答