Aldo
Aldo

Reputation: 346

Backbone: How to validate if a Model already exist in a Collection?

Given this Backbone Collection

define  [
  'underscore',
  'backbone',
  'cs!models/floor'
], ( _, Backbone, Floor ) ->
return Backbone.Collection.extend
  model: Floor
  url: ->
    return '/api/hotels/' + @hotelId + '/floors'
  initialize: (models, options) ->
    if ( options.hotelId )
      @hotelId = options.hotelId
      @.fetch()

  parse: (response) ->
    response.floors

  alreadyExist: ->
    @.filter( (floor) ->
      return floor.get('number') == @.attrs.get('number')
    )

and adding a new Model from a view the way below, how can I validate if the model already exist within the collection ?

add_floor: (e) ->
  console.log ' Saving Floor '
  e.preventDefault()
  floorNumber =  $('input[name=floorNumber]').val()
  floorDescription = $('input[name=floorDescription]').val()
  return new NoticeView({ message: "Please enter a Floor Number.", displayLength: 10000 }) unless floorNumber
  if ! @collection.add({ number: floorNumber}).alreadyExist()
    @collection.create({ number: floorNumber, description: floorDescription }, {
      error: (model, response) ->
        # $(e.target).removeClass('waiting');
        new ErrorView({ message: "Problem saving Floor " + response.responseText, displayLength: 10000 })
      success : (model, response) ->
        console.log model
        console.log response
        new NoticeView({ message: "Floor successfully saved.", displayLength: 10000 })
    })
  else 
    new ErrorView({ message: "Floor already exist." + response.responseText,        displayLength: 10000 })

Upvotes: 9

Views: 13072

Answers (2)

azakgaim
azakgaim

Reputation: 329

findWhere on a collection will not result in JavaScript error but will not not find a model neither. A proper way of checking if a collection contains a model is to use underscore's find like this:

var model = _.find(collection.models, function (model) { return model.id == 

id_to_be_searched; });
var found = collection.contains(model);

if (found) {
    // do stuff
}
else {
   // do stuff   
}

Upvotes: 0

dcarson
dcarson

Reputation: 2853

Backbone collections proxy the Underscore.js iteration functions which are useful in these cases.

If you have an existing model instance, to check whether it exists in the collection you can just do something like:

var myModel = new Floor();

// the following line logs true if model is in collection, false if not.
console.log(myCollection.contains(myModel));

If you do not have an existing instance of the model, which from your example suggests may be the case, you can use the find or findWhere underscore functions, for example:

var floorNumber =  $('input[name=floorNumber]').val()
var myModel = myCollection.findWhere({ floorNumber: floorNumber });

If find or findWhere return a model, which you could easily check using a typeof comparison then you will know whether the model exists in the collection or not.

Upvotes: 20

Related Questions