如何创建增强本机值绑定的自定义Knockout绑定

时间:2013-04-11 15:11:27

标签: knockout.js

我正在创建一个自定义绑定,用于在init方法中设置焦点和模糊行为。否则,我希望这个自定义绑定的运行方式与本机Knockout值绑定完全相同。

 ko.bindingHandlers.currencyValue = {

init: function (element, valueAccessor) {
    $(element).focus(function () {
        //focus behavior here...
    });

    $(element).blur(function () {
        //blur behavior here...
    });

   //what do I put here to get the native value binding behavior?
},
update: function (element, valueAccessor) {
    //what do I put here to get the native value binding behavior?
}

2 个答案:

答案 0 :(得分:2)

您应该致电ko.bindingHandlers.value.initko.bindingHandlers.value.update函数:

ko.bindingHandlers.currencyValue = {
init: function (element, valueAccessor, allBindings, viewModel, context) {
    $(element).focus(function () {
        //focus behavior here...
    });

    $(element).blur(function () {
        //blur behavior here...
    });

   return ko.bindingHandlers.value.init(element, valueAccessor, allBindings, viewModel, context);
},
update: function (element, valueAccessor, allBindings, viewModel, context) {
    return ko.bindingHandlers.value.update(element, valueAccessor, allBindings, viewModel, context);
}

答案 1 :(得分:0)

@Artem 更轻松,更易于维护和解读的解决方案 - 如果有一天KO会将额外参数传递给initupdate函数,这需要更少的击键次数:

ko.bindingHandlers.currencyValue = {
init: function (element, valueAccessor, allBindings, viewModel, context) {
    $(element).focus(function () {
        //focus behavior here...
    });

    $(element).blur(function () {
        //blur behavior here...
    });

   return ko.bindingHandlers.value.init.apply(this, arguments);
},
update: function (element, valueAccessor, allBindings, viewModel, context) {
    return ko.bindingHandlers.value.update.apply(this, arguments);
}