2013-03-26 62 views
0

使用時,我已經在骨幹網中定義像這樣一個模型,收集沒有定義:自定義字段中收集

$(document).ready(function() { 

DeviceModel = Backbone.Model.extend({ 
    urlRoot: '/ajax/mvcDevices', 

    validationRules: { 
     name: [{ rule: 'required'}], 
     mac: [ 
     { rule: 'required' }, 
     { rule: 'isMacAddress' } 
     ], 
     speed: [{ rule: 'required'}] 
    }, 

    preprocess: { 
     name: ['clean', 'trim'], 
     speed: ['clean', 'trim'] 
    } 
}); 

DeviceCollection = Backbone.Collection.extend({ 
    url: '/ajax/mvcDevices', 
    Model: DeviceModel 
}); 
}); 

然而,一個集合裏,這些模型時,列出的自定義字段都沒有定義的。我在這裏錯過了什麼?如果你創建一個new運營商defaults所有屬性將被複制到新的對象模型

var DeviceModel = Backbone.Model.extend({ 
    urlRoot: '/ajax/mvcDevices', 

    defaults: { 
     validationRules: { 
      name: [{ rule: 'required'}], 
      mac: [ 
      { rule: 'required' }, 
      { rule: 'isMacAddress' } 
      ], 
      speed: [{ rule: 'required'}] 
     }, 

     preprocess: { 
      name: ['clean', 'trim'], 
      speed: ['clean', 'trim'] 
     } 
    } 
}); 

var DeviceCollection = Backbone.Collection.extend({ 
    url: '/ajax/mvcDevices', 
    Model: DeviceModel 
}); 

var collection = new DeviceCollection(); 

var model = new DeviceModel({id: 1}); 
collection.add(model); 
console.log(collection.get(1).get('validationRules')); 
console.log(collection.get(1).get('preprocess')); 

從骨幹文檔,因此:

+1

'Model:DeviceModel' =>'model:DeviceModel'? (小寫'm') – WiredPrairie 2013-03-26 12:09:17

+0

@WiredPrairie(facepalm)就是這樣,一直注視着我的臉。非常感謝。 – Nidonocu 2013-03-26 13:48:46

回答

-1

您可以使用defaults模型屬性來執行這樣的默認值它取決於您創建模型對象的方式。

+0

啊..這裏的問題是這些值不是數據項,所以我不希望他們進入模型屬性併發送到服務器等等。他們是用於處理模型的驗證代碼的支持數據。 – Nidonocu 2013-03-26 13:44:10

+0

@Nidonocu:在這種情況下,您聲明它們的方式是正確的,它們應該可以作爲「標準」實例屬性(如so,modelInstance.attribute(例如modelInstance.validationRules))訪問。換句話說,不要通過Backbone.Model的get()來訪問它們。 – robmisio 2013-03-26 13:46:50