Knockout.js绑定范围

Knockout.js binding scope

在绑定处理程序的 initupdate 部分之间共享变量的最佳方法是什么?

ko.bindingHandlers.someBinding = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) 
    {
        // declare something here
    },
    update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) 
    {
        // use the variable here
    }   
}

我确定我不想污染视图模型本身。 我可以通过 jQuery.data() 将它附加到元素上,但感觉很难看。

knockout.js 中的自定义绑定只创建一次,因此这意味着如果您存储一些局部变量,它将被重新用于每个使用绑定的元素。如果这对您来说不是问题,下面是实现该目标的一种方法。

Knockout 绑定要求您 return 一个具有方法 initupdate 的对象。您可以使用示例中显示的对象文字,但您可以使用其他模式,例如 revealing module pattern:

// instead of using object literal, use IIFE (immediately invoked function expression:
ko.bindingHandlers.someBinding = (function(){
     // define your local variables, functions and anything else you need
     // keep in mind that the same variables will be re-used for EVERY
     //element where the binding is used
     var yourVariable = 0,

         // declare init and update methods
         init = function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) 
         {
            alert(yourVariable);   // displays 0
            yourVariable += 1;
         },
         update = function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) 
         {
            alert(yourVariable);   // displays 1
         };
    // return object literal with methods init and update
    return {
        init: init,
        update: update
    };
}());    // execute the function