Reputation: 28930
I have a question about this code:
getContent: (index) ->
content = @get('content')
element = content.objectAt(index)
if element?
[type, clientId] = element
store = @get('store')
if clientId?
store.findByClientId(type, clientId)
I am specifically talking about this line:
[type, clientId] = element
I do not understand how I can assign two values from one variable.
Would element have to be an array in order for the above to successfully assign values to the left hand side array?
Upvotes: 2
Views: 3134
Reputation: 1642
I do not understand how I can assign two values from one variable.
CoffeeScript implements what it calls Destructuring Assignment. See the full explanation at http://coffeescript.org/#destructuring, but I've pulled some examples from it to show here.
It can be used for simple list assignment.
weatherReport = (location) ->
# Make an Ajax request to fetch the weather...
[location, 72, "Mostly Sunny"]
[city, temp, forecast] = weatherReport "Berkeley, CA"
Where the destructuring assignment statement is compiled to
_ref = weatherReport("Berkeley, CA"), city = _ref[0],
temp = _ref[1], forecast = _ref[2];
Would element have to be an array in order for the above to successfully assign values to the left hand side array?
Nope, it can be used for objects as well. From the CoffeeScript docs "Destructuring assignment can be used with any depth of array and object nesting, to help pull out deeply nested properties."
futurists =
sculptor: "Umberto Boccioni"
painter: "Vladimir Burliuk"
poet:
name: "F.T. Marinetti"
address: [
"Via Roma 42R"
"Bellagio, Italy 22021"
]
{poet: {name, address: [street, city]}} = futurists
Where the destructuring assignment statement is compiled to
_ref = futurists.poet,
name = _ref.name, (_ref1 = _ref.address, street = _ref1[0], city = _ref1[1]);
Upvotes: 4
Reputation: 30473
That is syntactic sugar, that means:
type = element[0], clientId = element[1];
Also, you should know, that there is a place where you can see in what coffeescript is compiled: http://coffeescript.org/ (try coffeescript tab)
All your coffeescript code in javascript:
getContent: function(index) {
var clientId, content, element, store, type;
content = this.get('content');
element = content.objectAt(index);
if (element != null) {
type = element[0], clientId = element[1];
store = this.get('store');
if (clientId != null) {
return store.findByClientId(type, clientId);
}
}
}
Upvotes: 0