Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/422.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将函数传递到Backbone.js中的模型默认值_Javascript_Backbone.js_Coffeescript_Marionette - Fatal编程技术网

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
用作静态属性。谢谢