【问题标题】:How to update collection and view with new data from response?如何使用响应中的新数据更新集合和视图?
【发布时间】:2013-10-24 05:13:06
【问题描述】:

如何使用来自handleSliderChange() 的服务器的新数据更新帖子集合?当我尝试在$.getJSON 中使用fetch() 时,集合会被旧数据重置。

define ['jquery','backbone','app','views/posts/post_view','templates/posts/index'], 
($, Backbone, App, PostsView) ->
  class App.Views.Posts.IndexView extends Backbone.View
    template: JST["posts/index"]

    events:
      "slidechange #slider":   "handleSliderChange"

    initialize: () ->
      @options.posts.on('reset', @render, @)

    addAll: () ->
      @options.posts.each(@addOne, this)

    addOne: (post) ->
      view = new PostView({model: post})
      $(@el).find("#list").append(view.render().el)

    slider: ->
      $(@el).find("#slider").slider({})

    handleSliderChange: (e, ui) ->
      self = this
      $.getJSON "/posts?scope="+ui.value, (data) ->
        #how to update posts collection with 'data'?

    render: ->
      $(@el).html(@template(posts: @options.posts.toJSON()))
      @slider()
      @addAll()
      @

【问题讨论】:

    标签: backbone.js coffeescript backbone-views


    【解决方案1】:

    使用Collection.reset 将现有集合替换为新模型。假设来自“/posts?scope?ui”的响应是一个哈希数组,你可以使用:

    $.getJSON "/posts?scope="+ui.value, (data) ->
        self.collection.reset data
    

    请注意,Collection.fetch 有点像调用“getJSON”后跟“reset”,因此您可能需要考虑使用它。

    options = {}
    options["url"] = "/posts?scope="+ui.value
    @collection.fetch options
    

    【讨论】:

    • 感谢第二个选项,它好多了:)
    猜你喜欢
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    • 2017-05-04
    • 2019-04-02
    相关资源
    最近更新 更多