Reputation: 1420
In Discover Meteor, there's a point where we pass a parameter (title
or url
) to a template helper like this:
<div class="form-group {{errorClass 'title'}}">
...
...
<div class="form-group {{errorClass 'url'}}">
Then we define helpers that are aware of the parameter being passed, like this:
errorClass: function (field) {
return !!Session.get('postSubmitErrors')[field] ? 'has-error' : '';
}
The Session.get('key')[parameter]
syntax is confusing to me - why is the parameter not passed with the key, but outside the function, surrounded by brackets? I don't see examples of this syntax in the docs. Thanks.
Upvotes: 0
Views: 173
Reputation: 7517
So, in JavaScript we can access properties of an object like this:
foo.bar
This means:
foo
bar
.There exists an alternative syntax:
foo["bar"]
This means exactly1 the same.
Why do we need this alternative syntax? Well, it allows us to do cool things like this:
var foo = { bar: "Nero", baz: "Caligula"}
var field = "bar";
foo[field]; // Evaluates to "Nero"
field = "baz";
foo[field]; // Evaluates to "Caligula"
(and it is how indexing into an array works).
This can be easily extended to:
function accessFoo(field) {
return foo[field]; // with foo from previous example.
}
accessFoo("bar"); // evaluates to "Nero"
accessFoo("baz"); // evaluates to "Caligula"
I hope you can see the similarity of your code sample and my last example.
1: for practical purposes - maybe there are some slight differences. If so, I'd love to hear about them in the comments.
Upvotes: 1