Skip to content

Instantly share code, notes, and snippets.

@maxbeatty
Last active December 22, 2015 19:09
Show Gist options
  • Save maxbeatty/6517653 to your computer and use it in GitHub Desktop.
Save maxbeatty/6517653 to your computer and use it in GitHub Desktop.
Editing Backbone Model attributes that are arrays
class ArrfulModel extends Backbone.Model
editArray: (method) ->
# populate array of arguments from callee
calleeArgs = (i for i in arguments[1])
# what attribute are we editting?
attr = calleeArgs.shift()
# get returns reference so must clone
arr = _.clone @get(attr)
# apply method with any additional arguments
Array.prototype[method].apply arr, calleeArgs
# set and trigger change
@set attr, arr
# push allows for N updates so using `arguments` to allow for that
push: (attr) ->
@editArray 'push', arguments
# splice takes an optional arg to replace elements at the provided index
# using `arguments` to allow for N replacements
splice: (attr) ->
@editArray 'splice', arguments
class ArgfulView extends Backbone.View
events:
'click .js-add': 'add'
'click .js-remove': 'remove'
'change input.js-edit' : 'edit'
initialize: (options) ->
@model.bind 'change', @render, @
render: ->
@$el.html @template.render @model.toJSON()
@ # for chaining
add: ->
@model.push 'listicle', someDefault
remove: (e) ->
which = determineWhich e
@model.splice 'listicle', which, 1
edit: (e) ->
which = determineWhich e
newItem = prepareNewItem e
@model.splice 'listicle', which, 1, newItem
@maxbeatty
Copy link
Author

I came across a problem today where a Backbone model had an attribute that was an array and I would need to add, remove, and edit items in this attribute.

This is where most tutorials and SO answers would tell you to set the default attribute of that model to a collection and operate on that collection will all of the niceties Backbone provides. It sounds simple enough, but for my particular need it would have been overkill and introduced even more complexity. I say overkill because I wouldn't use any of the features of the collection besides it acting like an array. Both the collection and the model would have needed their own views which would have put me at 5 nested views. I didn't want to go there.

Instead, I wrote some functions abusing arguments to make it easy to add, remove, and edit from the view (see above). Some of the view code has been simplified for readability, but the model code is all in working order. I'm happy with it and will probably look to reuse it elsewhere.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment