2

I have a Json object that I'm dumping into a jQuery template (tmpl). It needs to be recursive because the Json object can be n-levels deep. This code works. However, if I wrap it in a function (it belongs in a jQuery plugin i'm writing), it stops working. To see what I mean simply uncomment the function wrapper in the Javascript.

Play with it: 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 ));

More info: I'm using RequireJS to load the files and kick off the whole process. I think that's what's killing the scope. Here's the code for that:

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 回答