[英]Knockout.js binding scope
在綁定處理程序的init
和update
部分之間共享變量的最佳方法是什么?
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綁定要求您返回具有init
和update
方法的對象。 您可以使用示例中顯示的對象文字,但您可以使用其他模式,例如顯示模塊模式 :
// 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.