Commits

Kenneth Jørgensen committed 4dd0054

Added basic `Collection` implementation

  • Participants
  • Parent commits 09a3417

Comments (0)

Files changed (3)

 ## 0.1.2-dev
 
 * Basic `Map` implementation.
+* Basic `Collection` implementation.
 * Removed `Models` default recursive JSON serialization.
 * Implemented default functions in `Model`.
 

File src/Collection.coffee

 Antifreeze.Collection = class Collection
+	constructor: ->
+		@_items = []
+
+	# Adds an element to the collection.
+	# Returns true if the element was added.
+	add: (obj) ->
+		@_items.push obj
+		# Fire change event.
+		@trigger "change",
+			type: "add"
+			map: @
+			value: obj
+		return true
+
+	# Removes a element from the collection.
+	# Returns true if the collection was altered by the remove.
+	remove: (obj) ->
+		index = @_getIndex(obj)
+		return false if index is false
+		# Remove element.
+		oldVal = @_items.splice(index, 1)[1]
+		# Fire change event.
+		@trigger "change",
+			type: "remove"
+			map: @
+			oldValue: oldVal
+		# Return old value.
+		return true
+
+	# Returns true of this collection contains the supplied element.
+	contains: (obj) ->
+		return @_getIndex(obj) isnt false
+
+	# Returns the sizxe of the collection.
+	size: (obj) ->
+		return @_items.length
+
 	toJSON: ->
-		json = super
-		for own val, key of json
-			if val instanceof Model or val instanceof Collection
-				json[key] = val.toJSON()
+		json = []
+		for o in @_items
+			json.push o
 		return json
+
+	# Returns the internal array index for the object, or false if it not found.
+	_getIndex: (obj) ->
+		for entry, i in @_items
+			if entry is obj
+				return i
+		return false

File src/Model.coffee

 		#for own key, val of json
 		#	if val and typeof val.toJSON is "function"
 		#		json[key] = val.toJSON()
-		return json
+		return json