自定义绑定不开火?

时间:2013-12-13 23:08:52

标签: jquery knockout.js knockout-2.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 个答案:

答案 0 :(得分:1)

它在这里工作,http://jsfiddle.net/YkeeB/(使用相同的代码) - 但它也使用Knockout 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部分。