如果模型属性是 ko.observable(),则可以在自定义绑定中按如下方式访问这些属性。
var observable = valueAccessor();
使用 Knockout-ES5 插件时,如何在自定义绑定中获取 observable?检查下面的代码并查找注释“如何在此处获取 propertyName?”
JS Fiddle 不使用 Knockout-ES 插件时由Another Look at Custom Bindings for KnockoutJS 提供
ko.bindingHandlers.datepicker = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
//initialize datepicker with some optional options
var options = allBindingsAccessor().datepickerOptions || {};
$(element).datepicker(options);
//handle the field changing
ko.utils.registerEventHandler(element, "change", function () {
var observable = valueAccessor();
if (!ko.isObservable(observable)) {
console.log("Not Observable");
//How to get propertyName here?
//ko.getObservable(viewModel, 'propertyName');
return;
}
observable($(element).datepicker("getDate"));
});
//handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).datepicker("destroy");
});
},
//update the control when the view model changes
update: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor()),
current = $(element).datepicker("getDate");
if (value - current !== 0) {
$(element).datepicker("setDate", value);
}
}
};
var viewModel = {
myDate: new Date("11/01/2011"),
setToCurrentDate: function() {
this.myDate = new Date();
}
};
ko.track(viewModel);
ko.applyBindings(viewModel);