Skip to content

Instantly share code, notes, and snippets.

@meagar
Last active December 29, 2015 08:09
Show Gist options
  • Save meagar/7641287 to your computer and use it in GitHub Desktop.
Save meagar/7641287 to your computer and use it in GitHub Desktop.
Allow Backbone's `get` to return multiple values

Improving Backbone's get to accept multiple arguments

CoffeeScript makes this work well:

[name, age] = user.get('name', 'age')

It would be trivially easy to allow Pam.Model's get to override Backbone's get to support this

Option 1: return array (not great)

get('name', 'age') could return ['john', '45'], allowing the following:

[name, age] = user.get('name', 'age')

Option 2: return object (better)

get('name', 'age') could return { name: 'john', age: 45 }, allowing both of the following:

{name, age} = user.get('name', 'age')

or

attrs = user.get('name', 'age')
printName(attrs.name)
printAge(attrs.age)

This is much more useful outside of the CoffeeScript world

Real world:

value = @get('value')
amount_unit = @get('amount_unit')
rate = @get('rate')
rate_unit = @get('rate_unit')
total = @get('total')
claim_type = @get('claim_type')

becomes

[value, amount_unit, rate, rate_unit, total, claim_type] =
  @get('value', 'amount_unit', 'rate', 'rate_unit', 'total', 'claim_type')

or

{value, amount_unit, rate, rate_unit, total, claim_type} =
  @get('value', 'amount_unit', 'rate', 'rate_unit', 'total', 'claim_type')

or

{value, amount_unit, rate,
rate_unit, total, claim_type} =
  @get('value', 'amount_unit', 'rate',
  'rate_unit', 'total', 'claim_type')
@meagar
Copy link
Author

meagar commented Nov 25, 2013

Generally we wouldn't be using huge blocks like the above example; it'd be most useful for destructuing assignment of 2 or 3 arguments:

{offset, startTime, endTime} = @get('offset', 'startTime', 'endTime');

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