如何从ko.bindingHandler中获取jquery.template内容?

时间:2011-12-16 14:30:46

标签: knockout.js jquery-templates

有一个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>

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

1 个答案:

答案 0 :(得分:0)

唯一的问题是在执行自定义绑定后呈现模板。您可以通过在setTimeout中执行init代码来处理此问题,例如:

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/