你可以這樣做,但這不是一個好主意。問題是當調用defaults
函數時,不能保證@
的狀態。該docs only say:
的默認哈希(或功能)可用於指定模型中的默認屬性。在創建模型的實例時,任何未指定的屬性都將設置爲其默認值。
沒有什麼在那裏,說@attributes
將在它什麼時候defaults
被稱爲所以@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/)
你會看到@attributes
空當defaults
被調用。這甚至是有道理的:你獲取默認值,合併來自構造函數調用的屬性,然後設置@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'作爲靜態屬性。謝謝! – ChrisG 2014-09-01 20:54:05