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

时间:2012-10-15 14:30:19

标签: backbone.js

鉴于此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')
    )

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

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 })

2 个答案:

答案 0 :(得分: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));

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

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

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

答案 1 :(得分:0)

findWhere集合不会导致JavaScript错误,但也不会找到模型。检查集合是否包含模型的正确方法是使用下划线查找:

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   
}