2011-04-13 31 views
2

我有一個Json對象,我傾倒到一個jQuery模板(tmpl)中。它需要遞歸,因爲Json對象可以是n級的。此代碼有效。但是,如果我將它包裝在一個函數中(它屬於我正在編寫的jQuery插件中),它將停止工作。看看我的意思是簡單的取消註釋Javascript中的函數包裝器。如何在我的插件之外製作遞歸jQuery模板(tmpl)?

玩它: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(); 
    }); 
}); 

回答

1

這是因爲你沒有將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"); 
})($); //######################## 
+0

好吧,你是對的。但我使用(jQuery)。我更新了代碼和jsfiddle以反映我實際在做什麼。這並沒有太大區別,但我不確定我是否理解如何使其工作......我已經使用了在jQuery插件創作頁面上推薦的創建插件的確切語法。 – dbme 2011-04-13 18:19:43

+0

新例子:http://jsfiddle.net/dbme/tkdZg/6/ – dbme 2011-04-13 18:26:30

+0

@dbme:你忘了調用插件方法。而已。我已經更新了jsfiddle帖子,包括一個電話,它的工作。檢查@ http://jsfiddle.net/tkdZg/8/ – Chandu 2011-04-13 19:22:25