【问题标题】:Spine.js, setting model default valuesSpine.js,设置模型默认值
【发布时间】:2013-03-30 10:31:17
【问题描述】:

在 Rails 中我们有生命周期钩子,它允许我们这样做:

class Subscription < ActiveRecord::Base
  before_create :record_signup

  private
    def record_signup
      self.signed_up_on = Date.today
    end
end

Spine.js 中是否有最好的方法来完成同样的事情(我需要它来设置一些默认值)?

目前我是这样做的,但也许有更好的方法存在?

class Subscription extends Spine.Model
    @record_signup: (self) ->
      self.signed_up_on = new Date()

Subscription.bind 'beforeSave', Subscription.record_signup

【问题讨论】:

    标签: coffeescript spine.js


    【解决方案1】:

    CoffeeScript 类主体是可执行的:

    class Subscription extends Spine.Model
        @record_signup: (self) ->
          self.signed_up_on = new Date()
    
        @bind 'beforeSave', @record_signup
    

    【讨论】:

    • 可以进一步简化为:@bind 'beforeSave', @record_signup?
    【解决方案2】:

    如果没有设置默认值,如何覆盖标准 Model.create 函数以包含默认值?

    @create: (atts, options) ->
      atts.myVal or= 'someDefault'
      record = new @(atts)
      record.save(options) 
    

    【讨论】:

    • 这看起来可行,我们可以用单个super line 替换 2 个底线吗?
    猜你喜欢
    • 2014-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-27
    • 2014-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多