使用Knockout-ES5时如何在自定义绑定中访问可观察对象 [英] How to access the observables in custom bindings when using Knockout-ES5
问题描述
如果模型属性为ko.observable(),则可以在自定义绑定中按以下方式访问这些属性.
If the model properties are ko.observable(), these can be accessed as below within the custom binding.
var observable = valueAccessor();
使用Knockout-ES5插件时,如何在自定义绑定中获得可观察的东西?检查下面的代码,并查找注释如何在此处获取propertyName?"
When using Knockout-ES5 plugin how to get hold of the observable within the custom binding? Check the code below and look for comment "How to get propertyName here?"
不使用Knockout-ES插件时,JS Fiddle 由 已更新小提琴,其模型已更改为使用Knockout-ES插件
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);
推荐答案
您可以将实际的observable传递给绑定:
You could pass the actual observable to the binding:
data-bind="datepicker: ko.getObservable($data, 'myDate') ..."
但这很丑.幸运的是,Knockout确实提供了一种从绑定中写入属性值的方法(未记录):
But that's ugly. Fortunately, Knockout does provide a way (undocumented) to write to a property value from a binding:
//handle the field changing
ko.utils.registerEventHandler(element, "change", function () {
var writable = valueAccessor();
if (!ko.isObservable(writable)) {
var propWriters = allBindingsAccessor()._ko_property_writers;
if (propWriters && propWriters.datepicker) {
writable = propWriters.datepicker;
} else {
return;
}
}
writable($(element).datepicker("getDate"));
});
这篇关于使用Knockout-ES5时如何在自定义绑定中访问可观察对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!