2012-11-29 150 views
4

我正在玩knockout.js来添加和删除表单中的字段。到目前为止它工作正常,但是我需要一个datepicker选项,所以我用jQuery的UI日期选择器。这是有效的,但仅限于第一个日期选择器,而不是其他地方。所以每当我点击'添加'我得到新的领域,但没有日期选择器。jQuery UI datepicker with Knockout.js

我使用Google搜索并搜索到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> 

Knockout.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 
}); 
}); 
+0

你尝试使用来自您链接的问题结合:HTTP:// stackoverflow.com/questions/6612705/knockout-with-jquery-ui-datepicker –

回答

9

使用自定义绑定处理CA ñ解决您的问题:

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/

+1

您可能还想要处理'update'函数,以便视图模型端的更改将反映在字段中,如在答案问题他连接 –

+0

谢谢!我要检查一下。我提出并接受了。 – mat

+0

该脚本的作品,谢谢你,但现在出现两个问题: 1.验证行为很奇怪。例如,它只适用于初始字段。 2.当点击字段外时,日期选择器保持活动状态。 – mat