2013-10-02 33 views
0

我有一個腳本,一旦啓動模式就會執行。 js配置js對象是:把手 - 無法讀取屬性undefined

var source = $("#print-script").html(); 
var template = Handlebars.compile(source); 
var data = { 
    image:  image, 
    title:  title, 
    caption:  subtitle, 
    category:  template 
}; 
$("#print-template").html(template(data)); 

所有變量都設置在對象聲明之上並且正在工作。我的html閱讀:

<script id="print-script" type="text/x-handlebars-template"> 
<div class="print-only" id="print-template"> 
    <img src="{image}"/> 
    <h2><span class="icon"></span>{category}</h2> 
    <h3>{title}</h3> 
    <p class="headline">{caption}</p> 
    <div class="description">{long_description}</div> 
</div> 
</script> 

我得到一個未捕獲的類型錯誤:無法讀取未定義的屬性'圖像'。我已確認對象(數據)正在填充內容。思考?

回答

3

我猜想,這個問題就在這裏:

var template = Handlebars.compile(source); 
var data = { 
    //... 
    category:  template // <------------------- oops 
}; 

注意template是編譯模板函數有所以當模板試圖填寫{category}時,它會執行template函數。但模板函數需要一些值來填充模板,然後通過{category}調用它們,那些值將不會在那裏,您將得到一個TypeError。運行這兩個演示與您的控制檯打開,你應該看到這是怎麼回事:

  1. 使用category: template錯誤:
    http://jsfiddle.net/ambiguous/9wEyS/
  2. 作品使用category: function() { return 'string' }
    http://jsfiddle.net/ambiguous/YgfZx/
0

原來有需要在該數據的另一對象:

var data = { print:{ 
        image:  featuredImage, 
        title:  title, 
        caption:  subtitle, 
        category:  template 
       } 
}; 
相關問題