2015-09-09 115 views
0

任何人都可以幫助我,JavaScript將函數'detect'定義爲undefined,我們如何從回調函數返回值來檢測函數?骨幹驗證和回調

validate: function (attrs, options) { 
    if (!this.detect(attrs.selectedFile, this.onComplete)) { 
     return "this is an error message"; 
    } 
}, 

detect: function (file, callback) { 
    var attributes = this.attributes, 
     image = new Image(); 
    image.onload = function() { 
     if (condition_is_false_return_false) { 
      callback(false); 
     } else { 
      callback(true); 
     } 
    }; 
    image.src = URL.createObjectURL(file); 
}, 

onComplete: function (value) { 
    return value; 
} 
+0

你有一個錯字:'this.detact'應該是'this.detect'。 – hindmost

+0

這不是解決方案。如果在發佈問題時發生了錯字,但在發佈問題時不會出現代碼 –

+0

_typo這是否意味着您在發佈問題時手動鍵入了此代碼?爲什麼不從源複製粘貼它(如果沒有輸入錯誤的話)? – hindmost

回答

0

代碼有兩個問題。 1.驗證函數只驗證attr候選者,這裏的「this」對象是不明確的,它可能不是模型。因此this.detect是未定義的。你可能不得不在下劃線中使用bind函數。

  1. 在設置屬性之前,驗證功能在技術上運行。因此,即使您可以成功調用detect函數,但在執行this.attributes時,您將獲得一個空集。所以你無法檢測到任何東西。這是更好地儘量讓這些功能的靜態的,這意味着它們沒有提及「本」

我做了一個jsfiddle

var myOwnModel=Backbone.Model.extend({ 

    initialize:function(model,options){ 
    Backbone.Model.prototype.initialize.apply(this,arguments); 
    }, 
    validate: function (attrs, options) { 
     console.log("doing validate",attrs); 
    if (!this.detect(attrs.selectedFile, this.onComplete)) { 
     return "this is an error message"; 
    } 
    }, 

    detect: function (file, callback) { 
     var attributes = this.attributes, 

      image = new Image(); 
        console.log("running detect",attributes) // Here attributes does not have the new attr. 
     image.onload = function() { 
      if (condition_is_false_return_false) { 
       callback(false); 
      } else { 
       callback(true); 
      } 
     }; 
     image.src = URL.createObjectURL(file); 
    }, 

    onComplete: function (value) { 
     return value; 
    } 

}) 

var a=new myOwnModel({a:1}) 
a.fetch(); 
// or test it with 
a.set({b:1},{validate:true}); 
console.log(a) 

貌似驗證確實有機會獲得「本」 。並且檢測功能正在成功運行。那麼問題是什麼?

+0

問題是,image.onload給我的寬度和高度,並在此基礎上我返回'真'或'虛假',但image.onload是異步方法,而我的驗證功能已經運行較早。其實我想驗證圖像尺寸驗證功能。 –