Skip to content

Instantly share code, notes, and snippets.

@Zenithar
Created August 14, 2012 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zenithar/3350751 to your computer and use it in GitHub Desktop.
Save Zenithar/3350751 to your computer and use it in GitHub Desktop.
Iterable Model for Backbone.js
MyCollection = require 'models/mycollections'
MyModel = require 'models/mymodel'
m1 = new MyModel({id: 1, label: 'tata'})
m2 = new MyModel({id: 14, label: 'tete'})
m3 = new MyModel({id: 2, label: 'titi'})
col = new MyCollection()
col.add m1
col.add m2
col.add m3
m1.hasPrevious() # false
m1.hasNext() # true
m1.nextElement().get("id") # 2
Model = require 'models/base/model'
module.exports = class IterableModel extends Model
_getCollectionIndex: () ->
throw Error("Model must be in a collection !") unless @collection?
@collection.indexOf @
hasNext: () ->
index = @_getCollectionIndex()
(index + 1) < @collection.length
hasPrevious: () ->
index = @_getCollectionIndex()
index > 0
nextElement: () ->
index = @_getCollectionIndex()
return null unless @hasNext()
@collection.at index + 1
previousElement: () ->
index = @_getCollectionIndex()
return null unless @hasPrevious()
@collection.at index - 1
Collection = require 'models/base/collection'
MyModel = require 'models/mymodel'
module.exports = class MyCollection extends Collection
model: MyModel
comparator: (model) ->
# Ceci va ordonner la collection sur l'attribut 'id' du modèle
model.get('id')
IterableModel = require 'models/base/iterablemodel'
module.exports = class MyModel extends IterableModel
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment