2015-04-23 24 views
1

我來自ruby/rails背景,所以我在圍繞UDEMY的骨幹課程練習中纏繞一些麻煩。有人可以告訴我我是否犯了錯誤,如果有的話如何解決?這次演習是關於收藏和我需要的輸出是console.logs學習backbone.js。我正確處理集合嗎?

var Vehicle = Backbone.Model.extend({ 

default: { 
    registrationNumber: "XXX-XXX", 
    color: "beige" 
} 

urlRoot: "/api/vehicle", 

start: function(){ 
    console.log("Vehicle started"); 
} 
}); 

var Vehicles = Backbone.Collection.extend({ 
model: Vehicle, 

url:"api/vehicles" 
}); 

var vehicles = new Vehicles([ 
new Vehicle({car1: {registrationNumber = "XLI887", color = "Blue"} }), 
new Vehicle({car2: {registrationNumber = "ZNP123", color = "Blue"}}), 
new Vehicle({car3: {registrationNumber = "XUV456", color = "Grey"}}) 
]); 

var blueCars = vehicles.where({ color: "Blue"}); 
var specificRegistration = vehicles.where({ registrationNumber:"XLI887"}); 

console.log("blue cars:", blueCars); 
console.log("Registration #:", specificRegistration); 


console.log("to JSON:", vehicles.toJSON()); 

Code Below:

+0

這將是一個小如果您以文本形式提供代碼而不是截屏,則可以更容易地爲代碼提供提示。 =) –

+0

我是相當新的stackoverflow。是否有一個捷徑來縮進網站上的整個代碼塊4空格?如果是的話,我將編輯... – Chris

+0

你可以在編輯器中添加縮進,並從它粘貼到stackoverflow –

回答

1

這是錯誤

new Vehicle({car1: {registrationNumber = "XLI887", color = "Blue" }}) 

,應

new Vehicle({registrationNumber: "XLI887", color: "Blue" }) 

或更換事件與此

{registrationNumber: "XLI887", color: "Blue" } 

因此Collection可以接受Model的數組,或者只接受含有數據的對象數組,這些數據將傳遞給集合中使用的模型構造函數。

您還可以使用Collection#findWhere只返回第一個發現的模型,而不是模型陣列像where

而且我發現你忘了後default部分添加昏迷

default: { 
    registrationNumber: "XXX-XXX", 
    color: "beige" 
}, // here should be a coma 
+0

所以car1是不必要的?如果我進行這些更改,它會執行嗎?謝謝您的幫助! – Chris

+0

這裏是一個工作jsfiddle http://jsfiddle.net/0a99trkr/你可以打開控制檯並運行它來查看結果 –