Backbone:如何验证模型中是否已存在模型?

Ald*_*ldo 9 backbone.js

鉴于此Backbone集合

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')
    )
Run Code Online (Sandbox Code Playgroud)

并从下面的视图添加新模型,如何验证模型是否已存在于集合中?

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 })
Run Code Online (Sandbox Code Playgroud)

dca*_*son 20

Backbone集合代理Underscore.js迭代函数,这些函数在这些情况下很有用.

如果您有一个现有的模型实例,要检查它是否存在于集合中,您可以执行以下操作:

var myModel = new Floor();

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

如果您没有模型的现有实例(可能是您的示例所示),则可以使用findfindWhere下划线函数,例如:

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

如果 findfindWhere返回一个模型,您可以使用typeof比较轻松检查,那么您将知道模型是否存在于集合中.