【问题标题】:Passing a function into a model default value in Backbone.js在 Backbone.js 中将函数传递给模型默认值
【发布时间】:2014-10-24 01:53:45
【问题描述】:

我希望模型的默认值调用这样的函数:

class Entities.Cart extends Backbone.Model
 defaults: =>
   tip:             0
   useStoreCredit:  @hasCredit()

 hasCredit: =>
   if @get('credit') > 0
     true
   else
     false

我知道默认值可以定义为函数as referenced in the Backbone docsin the Marionette docs。但是这些文档都没有提到在默认哈希中调用函数。这可能吗?

【问题讨论】:

    标签: javascript backbone.js coffeescript marionette


    【解决方案1】:

    您可以这样做,但这不是一个好主意。问题是当调用defaults 函数时,不能保证@ 的状态。 docs only say

    defaults 散列(或函数)可用于指定模型的默认属性。创建模型实例时,任何未指定的属性都将设置为其默认值。

    当调用defaults 时,其中没有任何内容表明@attributes 将包含任何内容,因此@get('credit') 可能会或可能不会返回有用的值。如果您检查当前行为:

    class M extends Backbone.Model
      defaults: ->
        console.log @toJSON()
        a: 'b'
    
    m  = new M
    mm = new M(a: 'c')
    

    (http://jsfiddle.net/ambiguous/6tjLuhrn/)

    当调用defaults 时,您会看到@attributes 为空。这甚至是有道理的:您获取默认值,从构造函数调用中合并属性,然后设置@attributes;当然,这些命令也有意义:

    • 使用默认值设置@attributes,然后合并到构造函数参数中。
    • @attributes 设置为构造函数参数,然后调用defaults 以获取未指定属性的值。

    基本上,当defaults 被调用时,您不能依赖@ 处于任何特定状态。

    但是,没有理由将useStoreCredit 作为静态属性。您可以根据需要提供自己的 toJSON 实现来计算它:

    toJSON: ->
      h = _(@attributes).clone() # This is the standard toJSON
      h.useStoreCredit = @get('credit') > 0
      h
    

    【讨论】:

    • 我最终做了类似于你回答的最后一部分的事情。因为useStoreCredit 需要是一个布尔值,所以我保留了default: useStoreCredit: false,然后我将使用useStoreCredit 作为静态属性。谢谢!
    猜你喜欢
    • 2015-01-11
    • 1970-01-01
    • 1970-01-01
    • 2012-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-16
    • 1970-01-01
    相关资源
    最近更新 更多