2012-07-10 67 views
1

我使用對象屬性作爲jQuery選擇有一個問題未定義存取jQuery選擇

define(["models/security/user", 'text!templates/security/registration.html'], function(SecurityUserModel, Template){ 

    var SecurityRegistrationView; 

    SecurityRegistrationView = Backbone.View.extend({ 
     initialize: function(){ 
      // setting model 
      this.model = new SecurityUserModel(); 

      // binding validation 
      Backbone.Validation.bind(this); 
      this.model.bind("validated:valid", this.valid); 
      this.model.bind("validated:invalid", this.invalid); 

      this.render(); 
     }, 
     form: { 
      "username": "#_user_username" 
      , "email": "#_user_email" 
      , "password": "#_user_password" 
     }, 
     render: function(){ 
      $(this.el).append(Template); 
     }, 
     events: { 
      "submit form": "submit" 
     }, 
     submit: function(e){ 
      e.preventDefault(); 

      this.model.set("username", $(this.form.username).val()); 
      this.model.set("password", $(this.form.email).val()); 
      this.model.set("email", $(this.form.password).val()); 
      this.model.validate(); 

      if (this.model.isValid) { 
       this.model.save(); 
      } 
     }, 
     valid: function(model, attrs){ 
      console.log(attrs[0]); 
      $(this.form[attrs[0]]).parent("div.control-group").addClass("success"); 
     }, 
     invalid: function(model, attrs){ 
      console.log(attrs[0]); 
      $(this.form[attrs[0]]).parent("div.control-group").addClass("error"); 
     } 
    }); 

    return SecurityRegistrationView; 
}); 
在鉻

控制檯輸出:

username registration.js:45 
Uncaught TypeError: Cannot read property 'username' of undefined registration.js:46 
password registration.js:45 
Uncaught TypeError: Cannot read property 'password' of undefined registration.js:46 
email registration.js:45 
Uncaught TypeError: Cannot read property 'email' of undefined registration.js:46 
username registration.js:45 
Uncaught TypeError: Cannot read property 'username' of undefined registration.js:46 



$(this.form.username).val(); // works 
$(this.form[someVar]); // does not work 
+0

id正確嗎? 發佈HTML代碼與表格 – Naigel 2012-07-10 11:29:55

回答

1

thisvalidinvalid回調可能並不是指你的看法。將您的initialize方法中的綁定修改爲適當的範圍:

this.model.bind("validated:valid", this.valid, this); 
this.model.bind("validated:invalid", this.invalid, this); 
+0

這適用,至少爲console.log;)。父級的jQuery命令文件(「div.control.group」)語句。 .parent(「div」)。parent(「div」)解決了這個問題:) – 2012-07-10 12:05:45

+0

如果你想避免.parent()。parent()我發現.closest(「div.control-group)只是旁邊:) – 2012-07-10 12:07:50

0

嘗試更換:

$(this.form.username) 

With:

$(this.form['username']) 

或者說,沒有 「這個」:

$(form['username']) 
  • 同爲 「密碼」 和 「電子郵件」。