Ember computed properties in Coffeescript

前端 未结 3 1165
醉酒成梦
醉酒成梦 2020-12-03 20:54

I want to implement the following Javascript code in Coffeescript

App.ItemView = Ember.View.extend({
    classNameBindings: [\'itemId\'],
    itemId: functio         


        
相关标签:
3条回答
  • 2020-12-03 21:31

    I like to use Ember.computed.

    itemId: Ember.computed 'firstName', 'lastName', ->
      "#{@get('firstName')} #{@get('lastName')}"
    
    0 讨论(0)
  • 2020-12-03 21:32
    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')
    
    0 讨论(0)
  • 2020-12-03 21:35

    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'    
    )
    
    0 讨论(0)
提交回复
热议问题