Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

backbone.js

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 })
like image 689
Aldo Avatar asked Oct 15 '12 14:10

Aldo


People also ask

Is Backbone JS still used?

Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.

How can we get the attribute value of a model in Backbone JS?

js Get model is used to get the value of an attribute on a model. Syntax: model. get(attribute)

What is collections in Backbone JS?

Collections are ordered sets of Models. We just need to extend the backbone's collection class to create our own collection. Any event that is triggered on a model in a collection will also be triggered on the collection directly.


1 Answers

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.

like image 76
dcarson Avatar answered Nov 07 '22 04:11

dcarson