2012-04-29 62 views
1

我正在使用backbone + jquery mobile,無法通過下劃線模板將我的模型(集合)數組輸出到UI。Binding backbone collection在前端查看和下劃線模板

我的模型如下:

var shortcake = Backbone.Model.extend({ 

    defaults: function() { 
     return { 
     name: "No Slot", 
     butter: false, 
     time: "3pm", 
     icon: "plus", 
     deladd: "ADD" 
     }; 
    }, 

    initialize: function() { 
     this.bind("change:butter", function(){ 
     if (this.model.butter == false) { 
     this.set({name: this.defaults.name}); 
     }; 
     }), 
    } 
}); 

我的收藏如下:

var shortcakes = Backbone.Collection.extend ({ 
    model: shortcake 
}); 

var shortcake1 = new shortcake({ name: "How Bizarre", butter: "true", time: "1", icon:"plus", deladd:"ADD" }); 
var shortcake2 = new shortcake({ name: "Sexual Healing", butter: "true", time: "1", icon:"plus", deladd:"ADD" }); 
var shortcakeAlbum = new shortcakes([ shortcake1, shortcake2]); 

而我的觀點:

var shortcakeUI = Backbone.View.extend ({ 

    tagName: "li", 
    template: _.template($('#shortcakeTemplate').html()), 


    initialize: function(){ 
    this.render(); 
    }, 

    render: function() { 
     var variables = { namee: name }; 
      if (this.model.butter == false) { 
      this.model.deladd = "ADD"; 
      this.model.icon= "plus"; 
      this.el.html(template); 
      } 
      else { 
       this.model.deladd = "DELETE"; 
      this.model.icon= "minus"; 
      this.el.html(template); 
      } 
     }, 

)}; 


var ShortcakeUI = new shortcakeUI({ 
collection : shortcakeAlbum, 
el: $("#shortcakeinterface")[0] 
}); 
ShortcakeUI.render(); 

而我的HTML是:

<ul data-role="listview" data-split-icon="gear" data-split-theme="d"> 
     <div id="shortcakeinterface"></div> 
    </ul> 
<!---Templates---> 
      <script id="shortcakeTemplate" type="text/template"> 
     <% for(var i = 0; i < shortcakeAlbum.length; i++){ %> 
     <% var shortcakez = shortcakeAlbum[i]; %> 

      <fieldset class="ui-grid-a"> 
       <div class="ui-block-a"> 

        <h3><%= shortcakez.time %></h3> 
        <p><%= shortcakez.name %></p>  

       </div> 

       <div class="ui-block-b"> 

        <div id="8" data-role="controlgroup" data-type="horizontal" > 
         <a href="#" data-role="button" data-icon="<%= shortcakez.icon %>"><%= shortcakez.deladd %></a> 
         <a href="#" data-role="button" data-icon="plus">Test</a> 
        </div> 

       </div>  
      </fieldset> 
     <% } %> 
     </script> 

所以對於這些,我的用戶界面不會顯示加載模型列表。 剛從骨幹和js開始,我在這裏做事情嗎?

回答

0

您需要將模型傳遞給render()中的模板。

而不是

this.el.html(template); 

做到這一點

$(this.el).html(this.template(this.model.toJSON())); 
+1

或'這個$ el.html ...'至極具有更好的性能,因爲在[jQuery的DOM實例化chached(HTTP:/ /documentcloud.github.com/backbone/#View-$el)。 – fguillen