2013-12-13 133 views
0

我想我的第一個自定義綁定在淘汰賽,但不能似乎得到它的工作。我從http://knockoutjs.com/documentation/custom-bindings.html得到了這個樣本。自定義綁定不會觸發?

腳本

ko.bindingHandlers.slideVisible = { 
    update: function (element, valueAccessor, allBindings) { 
     debugger; 
     // First get the latest data that we're bound to 
     var value = valueAccessor(); 

     // Next, whether or not the supplied model property is observable, get its current value 
     var valueUnwrapped = ko.unwrap(value); 

     // Grab some more data from another binding property 
     var duration = allBindings.get('slideDuration') || 400; // 400ms is default duration unless otherwise specified 

     // Now manipulate the DOM element 
     if (valueUnwrapped == true) $(element).slideDown(duration); // Make the element visible 
     else $(element).slideUp(duration); // Make the element invisible 
    } 
}; 

HTML

<div data-bind="slideVisible: giftWrap, slideDuration:600">You have selected the option</div> 
<label> 
    <input type="checkbox" data-bind="checked: giftWrap" />Gift wrap</label> 
<script type="text/javascript"> 
    var viewModel = { 
     giftWrap: ko.observable(true) 
    }; 
    ko.applyBindings(viewModel); 
</script> 

的jsfiddle鏈接:http://jsfiddle.net/dingen2010/2gpL6/1/

回答

1

它的工作在這裏,http://jsfiddle.net/YkeeB/(使用相同的代碼) - 但它也採用淘汰賽V3.0(其中是Knockout網站文檔中使用的示例)

ko.bindingHandlers.slideVisible = { 

    update: function (element, valueAccessor, allBindings) { 
     // First get the latest data that we're bound to 
     var value = valueAccessor(); 

     // Next, whether or not the supplied model property is observable, get its current value 
     var valueUnwrapped = ko.unwrap(value); 

     // Grab some more data from another binding property 
     var duration = allBindings.get('slideDuration') || 400; // 400ms is default duration unless otherwise specified 

     // Now manipulate the DOM element 
     if (valueUnwrapped == true) $(element).slideDown(duration); // Make the element visible 
     else $(element).slideUp(duration); // Make the element invisible 
    } 
}; 


    var viewModel = { 
     giftWrap: ko.observable(true) 
    }; 
    ko.applyBindings(viewModel); 

對於Knockout v2.3.0及更低版本,沒有方法ko.unwrap。相反,您必須使用ko.utils.unwrapObservable。這裏有一個小工具,用於v2.2.1,http://jsfiddle.net/yt4Gs/1/

另外,僅當將來使用JSFiddle時,請勿將腳本放在HTML部分 - 即使它在<script>標籤內。放入JavaScript部分。

相關問題