【问题标题】:Is it possible to only rerender a part of a template是否可以只重新渲染模板的一部分
【发布时间】:2014-10-26 02:28:32
【问题描述】:

我有一个带有 div 的模板 #entries#movies 在我的 #entries div 中,我展示了我的电影收藏的模型。在我的#movies div 中,我显示了搜索查询的结果。 (元素的命名很糟糕,我同意)。

在呈现模板的视图中,我有以下事件,

  events: -> 
    "click li": "addEntry" 
    "click .remove": "destroyEntry" 

  addEntry: (e) -> 
    movie_title = $(e.target).text()
    @collection.create title: movie_title

  appendEntry: (entry) ->
    view = new Movieseat.Views.Entry(model: entry)
    $('#entries').append(view.render().el)

  destroyEntry: (e) -> 
    thisid = @$(e.currentTarget).closest('div').data('id')
    @collection.get(thisid).destroy()

li 元素在#movies div 中呈现。这样我可以从不同的视图单击结果并将它们添加到其他集合中。这行得通,但有一个问题。

我也有这个观点,

  initialize: -> 
    @collection.on('change', @render, this)
    @collection.on('add', @appendEntry, this)
    @collection.on('destroy', @render, this)
    return

问题在于,当集合发生变化时(比如我在其中添加或删除电影时),它会重新呈现模板。这意味着它会重新渲染 #entries#movies div。但现在它只是呈现一个空的 #movies div(没有 searchquery 集合)。

所以我想知道是否可以只渲染模板的一部分。在这种情况下,我只想重新渲染 #entries div,只保留 #movies div。

【问题讨论】:

    标签: javascript jquery backbone.js


    【解决方案1】:

    你可以试试这个:

    @collection.on('change', @renderEntries, this)
    
    renderEntries: (entry) ->
        $('#entries').html(render('entries', { entries: yourEntriesCollection.toJSON() }))
    
    //some common.js file
    
    function render(template_name, data)
    {
        //here create logic to render specified template by name with data.
        // see example here: http://stackoverflow.com/questions/8366733/external-template-in-underscore
        return html;
    }
    

    您应该为可以单独呈现的条目创建模板。

    【讨论】:

    • 所以你是说当集合改变时执行renderEntries 函数。 renderEntries 函数使用集合中的内容更新 #entries div 的 html。 $('#entries').html(render 中的“渲染”部分是指function render(template_name, data) 吗?
    • 是的,渲染函数只是您可以创建的一些实用程序,以便在应用程序的任何位置使用它。
    • 嗯,我在理解$('#entries').html(render('entries',{entries: yourEntriesCollection.toJSON()})) 时遇到了一些麻烦,我用$('#entries').html('hello) 进行了尝试,它确实用hello 替换了当前的HTML。但我不明白如何将它与我用来输出数据的模板联系起来。我在不同的文件夹中有模板。我也不明白{ entries: yourEntriesCollection.toJSON() } 做了什么,或者为什么我需要它。
    • 您很遗憾只需要重新呈现您的条目。所以你需要以某种方式呈现你的条目集合。在建议的解决方案中,您需要将您的集合(以 toJSON() 格式)发送到某个渲染引擎,该引擎使用条目模板(您应该创建)
    猜你喜欢
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 2011-05-23
    • 2013-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多