2011-10-04 73 views
0

我向模型和集合添加了驗證將不會獲取無效的模型。 (順便說一句,我用coffeescript所以例子在咖啡腳本)Backbone.js集合將無法獲取無效的模型

有人知道這個解決方案嗎?下面的心不是工作

collection = new UserCollection 

collection.fetch({ 
    silent: true 
    success: -> 
    console.log('collection.models:', collection.models) 
}) 

更新1

我有很多用戶沒有手機號碼。

用戶收集:

class UserCollection extends Backbone.Collection 

    url: -> 
    app.routes.users_url 

用戶模型:

class User extends Backbone.Model 

    idAttribute: '_id' 

    defaults: { 
    "email": null 
    "mobile": null 
    "loc": null 
    } 

    url: -> 
    app.routes.users_url + '/' + (@id || '') 

    validate: (attrs) -> 
    if !attrs.email 
     return "Email address must be provided" 
    if !attrs.name 
     return "Name must be provided" 
    if !attrs.mobile 
     return "Mobile number must be provided" 
    if @isNew() and attrs.password != undefined 
     if !attrs.password 
     return "Password must be provided" 
     if attrs.password != attrs.password_confirmation 
     return "Passwords do not match" 
    model: User 

UPDATE 2

確定我臨時由黑客Backbone.js的固定它。

這是發生在功能_prepareModel

我改變了這一行:

if (model.validate && !model._performValidation(attrs, options)) model = false; 

進入這一行:

if (!options.silent && model.validate && !model._performValidation(attrs, options)) model = false; 

這是不是一個解決方案,所以我保留了這個問題開

+0

您是否嘗試過傳遞'error'回調函數?它會被叫嗎? –

+0

不打電話。 –

+0

你可以發佈你的模型和驗證碼嗎? –

回答

0
"I added a validation to a Model and a Collection wont fetch the models who arent valid. 
(Btw I use coffeescript so the examples are in coffeescript)" 

如果您的模型未驗證,您的模型或驗證有問題。

"I have a lot of users without a mobile number." 

在驗證您有:

if !attrs.mobile 
    return "Mobile number must be provided" 

,你可以在您的收藏定義解析功能,記錄哪些車型會從服務器(解析未來()獲取傳遞從讀取(原始響應))

parse: function(response) { 
    console.log(response.results); 
    return response.results; 
} 

,或者你可以採取的驗證手機號碼的存在,你的驗證線,因爲你不知道,如果用戶有一個手機號碼。

,只是涵蓋所有的基礎上,定義提取)的誤差函數(應該可以幫助您:

collection.fetch({ 
    silent: true 
    success: -> 
    console.log('collection.models:', collection.models) 
    error: (collection, response) -> 
    console.log('response') 
}) 
+0

問題是,即使我添加沉默:真,集合沒有獲取它們。 –

+0

值得注意的是,集合中的'parse'方法不一定會傳遞帶有'results'鍵的對象。這取決於你正在使用的API。 Twitter API使用'results'鍵傳遞一個對象,但是一個vanilla Backbone應用程序只傳遞一個模型數組。 – shennan

0

當您驗證模型,檢查model.silent,如果不存在唯一的驗證。

var test = new MyModel({ id: '123', silent: true }); 

// in your Model validate function 
validate: function(attrs) { 
    if (!attrs.silent) { 
    // validate logic here 
    } 
} 

然後你就可以獲取模型:

所以,當你想獲取一個模型,你做到以下幾點。獲得模型後,您可以取消沉默。