bonum_cete
bonum_cete

Reputation: 4962

Resetting/clearing a Backbone collection

I am fetching a backbone collection for a search form. I think I want to reset the collection after every search because currently the search results are just appending the new results the previous results.

Currently the @collection.reset() does absolutely nothing.

class ****.Views.DesignerSearchView extends Marionette.CompositeView

  className: 'tab_pane'

  id: 'search_items'

  template: JST['designer/DesignerSearchTemplate']


  itemView: (obj) ->
    new Mywebroom.Views.DesignerSearchItemsLayout(obj)

  itemViewContainer: "div"

  events: {
    'keyup #designer_search': 'search'
    'click .fa-times ': 'clearSearch'
  }

  initialize:->

    @collection = new Mywebroom.Collections.SearchItems()


  search: ->

    searchTerm = $('#designer_search').val()

    @collection.reset()
    @collection.fetch({
      data: $.param({ search : searchTerm })

      async: false
      success: (collection, response, options) ->
        console.log("designs fetch success", response)

      error: (collection, response, options) ->
        console.error("designs fetch fail", response.responseText)
    })

EDIT

Per CharlieBrowns suggestion:

search: ->

    searchTerm = $('#designer_search').val()

    @collection.fetch({
      data: $.param({ search : searchTerm })

      async: false
      reset: true
      success: (collection, response, options) ->
        console.log("designs fetch success", response)

      error: (collection, response, options) ->
        console.error("designs fetch fail", response.responseText)
    })

and

search: ->

    searchTerm = $('#designer_search').val()

    @collection.reset([])
    @collection.fetch({
      data: $.param({ search : searchTerm })

      async: false
      success: (collection, response, options) ->
        console.log("designs fetch success", response)

      error: (collection, response, options) ->
        console.error("designs fetch fail", response.responseText)
    })

But still no luck

Upvotes: 0

Views: 286

Answers (1)

CharlieBrown
CharlieBrown

Reputation: 4163

You have two options:

  1. Use collection.reset([]) to reset the collection and add 0 new models.
  2. Use collection.fetch({ reset: true }) to reset the collection on every fetch.

Upvotes: 1

Related Questions