2014-03-25 45 views
1

我實現了這個簡單的功能中的骨幹示範,以發現任何不想要的或不特定屬性:檢測骨幹模型驗證任何不需要的屬性

var Underscore = require('/usr/local/lib/node_modules/underscore'), 
    Backbone = require('/usr/local/lib/node_modules/backbone'), 
    Validation = require('/usr/local/lib/node_modules/backbone-validation'); 

Underscore.extend(Backbone.Model.prototype, Validation.mixin); 

var User = Backbone.Model.extend({ 
    validation: { 
     firstname: { 
      minLength: 1, 
      maxLength: 20, 
      required: true 
     }, 
     lastname: { 
      minLength: 1, 
      maxLength: 20, 
      required: true 
     } 
    }, 
    ... 

    isAttributeAccepted: function(attr) { 
     var retval = false; 
     for (var property in this.validation) { 
      if (attr == property) { 
       retval = true; 
       break; 
      } 
     } 
     return retval; 
    }, 
    ... 

在使用中:

var user = new User(); 
var isDesired = user.isAttributeAccepted("nop"); 
console.log(isDesired) // false; 

我只是做了它,因爲我無法在Backbone.validation中找到任何內容來替換它。 我怎樣才能用優先的方式替換此代碼來使用Backbone.validation(github thederson.com)?

謝謝。在backbone.validation

回答

1

我還沒有找到方法來做到這一點,但你可以寫你的代碼稍微容易一些:

isAttributeAccepted: function(attr) { 
     return _.has(this.validation, attr); 
    }, 
+0

這是一種進步。謝謝。 – Alain