简体   繁体   中英

How to reproduce correct JavaScript object literal property that is an anonymous function from CoffeeScript?

I have the following valid javascript:

App.Person = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
birthday: DS.attr('date'),

fullName: function() {
    return this.get('firstName') + ' ' + this.get('lastName');
  }.property('firstName', 'lastName')
});

According to js2coffee.org This js is the equivalent of the following coffee script :

App.Person = DS.Model.extend(
  firstName: DS.attr("string")
  lastName: DS.attr("string")
  birthday: DS.attr("date")
  fullName: ->
    @get("firstName") + " " + @get("lastName")
  .property("firstName", "lastName")
)

However that same coffee script does not compile back down into valid javascript. It is not even valid coffee script as it errors with "Unexpected '.' "

How can I write valid Coffee Script that will create the same or syntactically equivalent javascript as listed above ?

Coffeescript:

App.Person = DS.Model.extend(
  firstName: DS.attr("string")
  lastName: DS.attr("string")
  birthday: DS.attr("date")
  fullName: ( ->
    @get("firstName") + " " + @get("lastName")
  ).property("firstName", "lastName")
)

Which compiles to:

App.Person = DS.Model.extend({
  firstName: DS.attr("string"),
  lastName: DS.attr("string"),
  birthday: DS.attr("date"),
  fullName: (function() {
    return this.get("firstName") + " " + this.get("lastName");
  }).property("firstName", "lastName")
});

Is there anyway to make it like this :

class App.Person extends DS.Model
    name: DS.attr

I know that it doesn't work with this syntax but I would like to use Coffee's class syntax

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM