9

鉴于此骨干集合

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

2 回答 2

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

如果您没有模型的现有实例,您的示例表明可能是这种情况,您可以使用findor findWhereunderscore 函数,例如:

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

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

于 2013-04-11T05:04:06.450 回答
0

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

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   
}
于 2017-08-11T16:36:09.277 回答