2

jQueryテンプレート(tmpl)にダンプしているJsonオブジェクトがあります。Jsonオブジェクトはnレベルの深さになる可能性があるため、再帰的である必要があります。このコードは機能します。ただし、関数でラップすると(私が書いているjQueryプラグインに属している)、機能しなくなります。私が何を意味するかを理解するには、Javascriptの関数ラッパーのコメントを解除するだけです。

それで遊んでください:http://jsfiddle.net/dbme/tkdZg/6/

HTML:

<script id="evntTemplate" type="text/x-jquery-tmpl">

{{if data.identifiers}}
<div id="${data.identifiers.id}" class="bsa-event">
    type: ${data.identifiers.type}<br />
    id: ${data.identifiers.id}<br />
    {{if children}}
        {{each(i, child) children}}
        <blockquote>
            <p>        
            {{if children}}
               {{tmpl(children) "evntTemplate"}}
            {{/if}}
            </p>
        </blockquote>
        {{/each}}
    {{/if}}  
</div>
{{/if}}
</script>
<div id="eventList"></div>

Javascript:

//(function ($) {
//    $.fn.SomePlugin = function() {
var movies = {
    "data": {
        "identifiers":{
            "type":0, "id":"makeunique_907827h"
        }
    },
    "children": {
        "data": {
            "identifiers": {
                "type":1, "id":"makeunique_716786g"
            }
        },
        "children": {
            "data": {
                "identifiers": {
                    "type":1, "id":"makeunique_234355g"
                }
            }
        }        
    }
};

/* Render the template with the data */
var evntTemplate = $( "#evntTemplate" ).template( "evntTemplate" );
$.tmpl(evntTemplate, movies).appendTo("#eventList");
    //};
//}( jQuery ));

詳細:RequireJSを使用してファイルをロードし、プロセス全体を開始しています。それがスコープを殺しているのだと思います。そのためのコードは次のとおりです。

require(["jquery", "jquery.tmpl", "jquery.someplugin"], function($) {
    $(function() {
        $('body').SomePlugin();
    });
});
4

1 に答える 1

0

これは、jqueryオブジェクトをパラメーターとして関数ラッパーに渡していないためです。

実例:http://jsfiddle.net/tkdZg/3

次のように変更します。

(function($) {
var movies = {
    "data": {
        "identifiers":{
            "type":0, "id":"makeunique_907827h"
        }
    },
    "children": {
        "data": {
            "identifiers": {
                "type":1, "id":"makeunique_716786g"
            }
        },
        "children": {
            "data": {
                "identifiers": {
                    "type":1, "id":"makeunique_234355g"
                }
            }
        }        
    }
};

/* Render the template with the data */
var evntTemplate = $( "#evntTemplate" ).template( "evntTemplate" );
$.tmpl(evntTemplate, movies).appendTo("#eventList");
})($); //########################
于 2011-04-13T18:10:26.623 に答える