【问题标题】:How can I reach jquery.template contents from within ko.bindingHandler?如何从 ko.bindingHandler 中访问 jquery.template 内容?
【发布时间】:2011-12-16 14:30:45
【问题描述】:

有一个带有knockout.js 绑定的元素(让它成为“A”)。该元素的内容是使用 knockout.js/jquery.tmpl 模板生成的。是否可以从元素“A”上调用的绑定处理程序中获取这些内容?

这是一个简单的例子:

<html>
    <head>      
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
        <script src="http://cloud.github.com/downloads/SteveSanderson/knockout/jquery.tmpl.js"></script>
        <script src="http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-1.3.0beta.debug.js"></script>
    </head>
    <body>
        <!-- Some simple tmpls -->
        <script id="wrapperTmpl" type="text/html">
            <div data-bind="showBug:true">                
                <div data-bind="template: 'buggyTmpl'"></div>               
            </div>
        </script>

        <script id="buggyTmpl" type="text/html">
            <div class="buggy">I am out of reach.</div>
        </script>

        <!--
            Knockout won't handle{{tmpl}} calls which are not wrapped in knockout constructions.
        -->
        <div data-bind="template: 'wrapperTmpl'"></div>

        <script>
            <!-- Refers to elements from the child rendered using tmpl -->
            ko.bindingHandlers.showBug = {
                init: function (elem, valueAccessor, allBindingAccessors, model) {
                    var $buggyElem = $(".buggy", elem);
                    console.log("$(elem).html(): ", $(elem).html());        
                    console.log("$('.buggy'): ", $buggyElem);

                }
            };


            ko.applyBindings({});       
        </script>
    </body>
</html>

如果有任何帮助,我将不胜感激。

【问题讨论】:

    标签: knockout.js jquery-templates


    【解决方案1】:

    唯一的问题是模板会在您的自定义绑定执行后呈现。您可以通过在 setTimeout 中执行初始化代码来解决这个问题,例如:

    ko.bindingHandlers.showBug = {
        init: function (elem, valueAccessor, allBindingAccessors, model) {
            setTimeout(function() {
                var $buggyElem = $(".buggy", elem);
                console.log("$(elem).html(): ", $(elem).html());        
                console.log("$('.buggy'): ", $buggyElem);           
            }, 0);
        }
    };
    

    http://jsfiddle.net/rniemeyer/njaeF/

    【讨论】:

    • 谢谢你,@RPNiemeyer。超时是一种可能的解决方法,但是否有一些处理类似示例的常见做法?
    • 除了使用afterRender 回调之外,实际上没有其他模式可以处理这种情况。模板需要先渲染,然后才能对元素进行操作。
    猜你喜欢
    • 2013-05-12
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-21
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多