2013-05-10 99 views
0

我想創建一個「fadeInIf」自定義綁定。我的想法是來自於「fadeVisible」的東西等於:http://knockoutjs.com/examples/animatedTransitions.html可能在Knockout中創建自定義綁定

// Here's a custom Knockout binding that makes elements shown/hidden via jQuery's fadeIn()/fadeOut() methods 
// Could be stored in a separate utility library 
ko.bindingHandlers.fadeVisible = { 
    init: function(element, valueAccessor) { 
     // Initially set the element to be instantly visible/hidden depending on the value 
     var value = valueAccessor(); 
     $(element).toggle(ko.utils.unwrapObservable(value)); // Use "unwrapObservable" so we can handle values that may or may not be observable 
    }, 
    update: function(element, valueAccessor) { 
     // Whenever the value subsequently changes, slowly fade the element in or out 
     var value = valueAccessor(); 
     ko.utils.unwrapObservable(value) ? $(element).fadeIn() : $(element).fadeOut(); 
    } 
}; 

我很新的自定義綁定,但認爲它可能是這樣的:

ko.bindingHandlers.fadeInIf = { 
    init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { 
     var value = valueAccessor(); 
     $(element).toggle(ko.utils.unwrapObservable(value)); 

     ko.bindingHandlers.if.init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext); 
    }, 
    update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { 
     var value = valueAccessor(); 
     if (ko.utils.unwrapObservable(value)) 
      $(element).fadeIn(); 

     ko.bindingHandlers.if.update(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext); 
    } 
}; 

我有「fadeVisible」工作,但不能工作這一個,我錯過了什麼?

回答

2

感謝您的建議。 我終於搞定了,我錯過了controlsDescendantBindings選項。結果如下:

ko.bindingHandlers.fadeIf = { 
    init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { 

     var value = valueAccessor(); 
     $(element).toggle(ko.utils.unwrapObservable(value)); 

     ko.bindingHandlers['if'].init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext); 
     return { controlsDescendantBindings: value }; 
    }, 
    update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { 
     var value = valueAccessor(); 
     if (ko.utils.unwrapObservable(value)) { 
      ko.bindingHandlers['if'].update(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext); 
      $(element).fadeIn(); 
     } 
     else { 
      $(element).fadeOut(200, function() { 
       ko.bindingHandlers['if'].update(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext); 
      }); 
     } 
    } 
}; 
0

我覺得你在99%的時候就明白了,但是淡入在第一次之後就不會做了......我認爲它與「if」綁定處理程序的工作方式有關。我所做的就是要改變這樣的:

if (ko.utils.unwrapObservable(value)) 
     $(element).fadeIn(); 

到這一點:

if (ko.utils.unwrapObservable(value)) { 
     $(element).toggle(false); 
     $(element).fadeIn(); 
    } 

我已經保存它的fiddle工作,如果你想查詢。

相關問題