答案 0 :(得分:0)
ko.applyBindingAccessorsToNode
将绑定的名称应用为字符串,以便您可以使用它来动态应用绑定。您可以在事件中使用javascript中的javascript,也可以在html中创建自定义绑定以使用它。自定义绑定可能如下所示:
ko.bindingHandlers.applyBinding = {
init: function(element, valueAccessor, allBindingsAccessor, data, bindingContext) {
var bindingName = ko.unwrap(valueAccessor());
var target = ko.unwrap(allBindingsAccessor().bindingTarget);
if (bindingName) {
var binding = {};
binding[bindingName] = function() {
return target;
};
ko.applyBindingAccessorsToNode(element, binding, bindingContext);
}
}
}
您可以在像<span data-bind="applyBinding: MyBinding, bindingTarget: myValue"></span>
您的代码仍然给我留下了很多问题,所以我无法确定这对您有用。您链接的示例除了绑定之外还有很多问题,因此我必须做出一些假设来修复错误并使其正常工作,但这是基于您的代码的示例:jsFiddle
答案 1 :(得分:0)
更新了包含数字和文本的逻辑。 https://jsfiddle.net/swvo7u00/4/
ko.bindingHandlers.numericText = {
init: function (element, valueAccessor, allBindingsAccessor) {
//element -> value
ko.utils.registerEventHandler(element, "change", function () {
var target = valueAccessor();
var newValue = $(element).val();
if (ko.isObservable(target)) { target(newValue); } else { target = newValue; }
});
},
update: function (element, valueAccessor, allBindingsAccessor, data, bindingContext) {
//model -> element
var value = ko.utils.unwrapObservable(valueAccessor());
if (typeof value === "number")
{
var precision = ko.utils.unwrapObservable(allBindingsAccessor().precision) || 2;
$(element).text(value.toFixed(precision));
}
else
{
$(element).text(value);
}
}
}