I want to implement the following Javascript code in Coffeescript
App.ItemView = Ember.View.extend({
classNameBindings: ['itemId'],
itemId: function() {
console.log(this.get('content'));
return "item-%@".fmt(this.get('content.id'));
}.property('content.id'),
templateName: 'item'
});
Here is what I have so far in coffeescript:
App.ItemView = Ember.View.extend(
classNameBindings: ['itemId']
itemId: ->
console.log this.get('content')
contentId = this.get('content.id')
"item-#{contentId}");
.property('content.id')
templateName: 'item'
)
I get:
Error: Parse error on line 11: Unexpected '.'
The issue seems to be with the dot in .property('content.id')
. I dont know how this translates into Coffeescript. How can I properly implement this view in Coffeescript?
What are Computed Properties? In a nutshell, computed properties let you declare functions as properties. You create one by defining a computed property as a function, which Ember will automatically call when you ask for the property. You can then use it the same way you would any normal, static property.
The computed property names feature was introduced in ECMAScript 2015(ES6) that allows you to dynamically compute the names of the object properties in JavaScript object literal notation. A JavaScript object is just a collection of key-value pairs called properties.
If you are looking to implement coffee script in html, take a look at this. You simple need to add a <script type="text/coffeescript" src="app. coffee"></script> to execute coffee script code in an HTML file.
It's beeing a quite long time, but I think this should be written like this:
App.ItemView = Ember.View.extend(
classNameBindings: ['itemId']
itemId: (->
console.log this.get('content')
contentId = this.get('content.id')
"item-#{contentId}");
).property('content.id')
templateName: 'item'
)
itemId: (->
content = @get 'content'
if content
return 'item-%@'.fmt(content.get 'id')
null
).property('content.id')
You have to protect computed properties from values that might not be defined yet. That is, your code is fine if there's already an id property on the content object. If content is undefined, then you're not going to be able to look up its ID property and you'll probably see a complaint.
You can also use
itemId: Ember.computed(->
..
).property('content.id')
and a similar pattern for observers. In fact, an observer would also accomplish the same thing without the conditional:
itemId: null
contentIdChanged: (->
@set 'itemId', 'item-%@'.fmt(@get 'content.id')
).observes('content.id')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With