2017-02-13 54 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 –

相关问题