Javascript 将函数传递到Backbone.js中的模型默认值
我希望模型的默认值调用如下函数:Javascript 将函数传递到Backbone.js中的模型默认值,javascript,backbone.js,coffeescript,marionette,Javascript,Backbone.js,Coffeescript,Marionette,我希望模型的默认值调用如下函数: class Entities.Cart extends Backbone.Model defaults: => tip: 0 useStoreCredit: @hasCredit() hasCredit: => if @get('credit') > 0 true else false 我知道默认值可以定义为函数和。但这两个文档都没有引用调用默认哈希中的函数。这可能吗
class Entities.Cart extends Backbone.Model
defaults: =>
tip: 0
useStoreCredit: @hasCredit()
hasCredit: =>
if @get('credit') > 0
true
else
false
我知道默认值可以定义为函数和。但这两个文档都没有引用调用默认哈希中的函数。这可能吗?你可以这样做,但这不是一个好主意。问题是调用
defaults
函数时,无法保证@
的状态。委员会:
defaults散列(或函数)可用于指定模型的默认属性。创建模型实例时,任何未指定的属性都将设置为其默认值
其中没有任何内容表明当调用默认值时,@attributes
将包含任何内容,因此@get('credit')
可能返回也可能不返回有用的值。如果检查当前行为:
class M extends Backbone.Model
defaults: ->
console.log @toJSON()
a: 'b'
m = new M
mm = new M(a: 'c')
()
当调用defaults
时,您将看到@attributes
为空。这甚至是有意义的:您获取默认值,合并构造函数调用中的属性,然后设置@attributes
;当然,这些命令也有意义:
- 使用默认值设置
@属性
,然后合并到构造函数参数中
- 将
@attributes
设置为构造函数参数,然后调用defaults
获取未指定属性的值
基本上,当调用defaults
时,您不能依赖@
处于任何特定状态
但是,没有理由将useStoreCredit
作为静态属性。您可以根据需要提供自己的toJSON
实现来计算它:
toJSON: ->
h = _(@attributes).clone() # This is the standard toJSON
h.useStoreCredit = @get('credit') > 0
h
我最后做了一些类似于你答案最后一部分的事情。由于useStoreCredit
需要是一个布尔值,因此我保留了默认值:useStoreCredit:false
,然后将useStoreCredit
用作静态属性。谢谢