2017-02-13 52 views
0

我得到2個模板:一個用於表單,另一個用於的結果。這是我的觀點。表單正在顯示,但是當我有一個時,我只會得到該行的一個靜態模板,我的意思是<% = key %>不起作用,窗體消失。使用jQuery.load在另一個模板中顯示模板

APP.FromFront = Backbone.View.extend({ 
    el: $("#content"), 
    events: { 
     "click #addLink" : "addLink", 
     "click .deleteLink" : "deleteLink" 
    }, 
    template: _.template($('#content').html()), 

    initialize: function() { 
     this.bookmarks = new APP.BookmarksCollection(); 
     this.render(); 
    }, 
    render: function() { 
     this.$el.html(this.$el.load("../../templates/form_template.html")); 
     this.bookmarks.each(function(bookmark) { 
      var bookJSON = bookmark.toJSON(); 
      **//############ this is where it's doesn't work** 
      var temp=_.template(this.$el.load("../../templates/links_template.html")); 
      $("#links").append(temp(bookJSON)); 
     },this); 
    }, 
}) 
+0

爲什麼你有一個未使用的'template:_.template($('#content')。html()),'?你爲什麼要加載外部文件而不是使用它?你知道['load'](http://api.jquery.com/load/)是如何工作的嗎?通過諸如'this。$ el.html(this。$ el.load(url))之類的代碼判斷''我不這麼認爲。你是否意識到我們的代碼試圖一次又一次地獲取相同的模板?儘管瀏覽器可能會緩存它,但這不是一個好習慣。 ['load'](http://api.jquery.com/load/)是異步的。請先閱讀文檔。 –

+0

感謝您的回答。當我的模板位於index.html頁面時,我使用了模板「template」。它在這段代碼中未被使用。 我真的不想加載它,但使用它。我知道如果它在index.html中,但不在其他文件中,該怎麼做。 – BoltMaud

回答

2

load是異步的。你需要這樣處理。您也應該在模板加載後緩存模板,而不是嘗試重複獲取相同的模板。嘗試如下:

APP.FromFront = Backbone.View.extend({ 
    el: $("#content"), 
    events: { 
    "click #addLink": "addLink", 
    "click .deleteLink": "deleteLink" 
    }, 
    initialize: function() { 
    this.bookmarks = new APP.BookmarksCollection(); 
    this.formTemplatePromise = $.get("../../templates/form_template.html"); 
    this.linkTemplatePromise = $.get("../../templates/links_template.html"); 
    $.when(this.formTemplatePromise, this.linkTemplatePromise) 
    .then(function(formTemplate, linkTemplate) { 
     this.formTemplate = _.template(formTemplate); 
     this.linkTemplate = _.template(linkTemplate); 
     this.render(); 
    }.bind(this)); 
    }, 
    render: function() { 
    this.$el.html(this.formTemplate(/* form data here? */)); 
    var links = []; 
    this.bookmarks.each(function(bookmark) { 
     // below code can be made a 1 liner, I split it for readability 
     var bookJSON = bookmark.toJSON(); 
     var link = this.linkTemplate(bookJSON); 
     links.push(link); 
    }, this); 
    // Single append instead of many for performance 
    $("#links").append(links); 
    } 
}); 
+0

我沒有formTemplate的數據。我嘗試了你的建議,但它不起作用。 我真的經常得到錯誤「n從undecorecore-min.js未定義」,並且我的代碼中有「n.replace不是函數」 再次感謝您 – BoltMaud

+0

使用此選項我沒有得到表格 – BoltMaud

+0

@ BoltMaud你正在使用什麼版本的下劃線?我認爲你正在使用最新版本。有一個API的變化,看到這個答案http://stackoverflow.com/a/25881231/2333214 –

相關問題