Reputation: 1665
Since I can't use the hash's values until they're defined, I was doing this:
@Foo =
Protocol: "http"
Domain: "foo.com"
# Annoying...
@Foo.Url = "#{Foo.Protocol}://#{Foo.Domain}"
Ideally, I'd be doing something like this (one motion):
# Doesn't work obviously...
@Foo =
Protocol: "http"
Domain: "foo.com"
Url: "#{Foo.Protocol}://#{Foo.Domain}"
Is there any way to do this?
The best methods I can come up with are:
Using Closures
@Foo = do =>
protocol = "http"
domain = "foo.com"
url = "#{protocol}://#{domain}"
protocol: protocol
domain: domain
url: url
Using $.extend
$.extend @Foo =
protocol: "http"
domain: "foo.com"
,
url: "#{Foo.protocol}://#{Foo.domain}"
Thanks,
Erik
Upvotes: 0
Views: 48
Reputation: 646
One option is to use functions instead of properties.
@Foo =
Protocol: -> "http"
Domain: -> "foo.com"
Url: -> "#{this.Protocol()}://#{this.Domain()}"
@Foo.Url() == "http://foo.com"
Or, if you wanted to use regular javascript, you could use a getter
Foo = {
Protocol: 'http',
Domain: 'foo.com',
get Url() {
return this.Protocol + '://' + this.Domain;
}
}
Foo.Url == 'http://foo.com'
Foo.Protocol = 'https'
Foo.Url == 'https://foo.com'
Upvotes: 1