2014-02-28 177 views
0

我是BackboneJS的新手。在編寫多個GET實現後,我試圖用Backbone JS實現登錄屏幕。
骨幹登錄屏幕

文件夾結構
應用
- >模型
- >查看
- >模板
- >服務器

formSignIn.html

<form class="form-signin" role="form"> 
<h2 class="form-signin-heading">Please sign in</h2> 
<input type="email" id="email" class="form-control" placeholder="Email address" required="" autofocus=""> 
<input type="password" id="password" class="form-control" placeholder="Password" required=""> 
<label class="checkbox"> 
    <input type="checkbox" value="remember-me"> Remember me 
</label> 
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button> 
</form> 

Backb一個查看

var SignInView = Backbone.View.extend({ 
    el:$('.container'), 
    template:_.template('../templates/formSignIn.html'), 
    events: { 
     "click .btn":"signIn" 
    }, 
    initialize: function() { 
     this.model.on('change', this.render, this); 
    }, 
    render: function() { 
     var attributes = this.model.toJSON(); 
     this.$el.html(this.template(attributes)); 
    }, 
    signIn: function() { 
     this.model.signIn({ 
     email: $('#email').val(), 
     password: $('#password').val() 
     }); 
    } 
}); 
var signInView = new SignInView({model: signInModel}); 
signInView.render(); 

骨幹示範

var SignInModel = Backbone.Model.extend({ 
    url:function() { 
     'http://localhost:3000/singIn' 
    }, 
    defaults: { 
     email:"", 
     password:"" 
    }, 
    parse: function(resp) { 
     return resp; 
    }, 
    signIn: function() { 
     this.save(); 
    } 
}); 
var signInModel = new SignInModel(); 

問題:

  1. HTML模板不渲染。當我打開頁面時,顯示../templates/formSignIn.html。這意味着_template不能識別該html。

  2. 視圖和模型如何實現?這是正確的做法嗎?我對調用模型的save()不是很有信心。

+0

我的回答有幫助嗎?如果是這樣,請考慮將其標記爲正確的答案。 – bejonbee

回答

0

在回答你的第一個問題_.template(...)需要一個字符串。如果您需要../templates/formSignIn.html的內容,您必須將其包含在dom中或請求它,例如使用ajax。

如果包括在DOM它看起來像這樣的東西吧:

// Somewhere in the html... 
<script type="text/html" id="form-signin-tpl"> 
    <form class="form-signin" role="form"> 
    ... 
    </form> 
</script> 

// in your view 
_.template($('#form-signin-tpl').html()); 

如果您需要在運行時要求的模板,你可以用它很好地處理這個RequireJS,或者你可以手動使用jQuery提出要求也許是這樣的:

$.get("path/to/templates/formSignIn.html", function(html) { 
    var tpl = _.template(html); 
}); 

在回答第二個問題

  1. 該模型的url參數是一個字符串,而不是一個函數。
  2. 如果您需要定製如何解析服務器的數據,則只需要定義parse

這可能是更你要什麼:

var SignInModel = Backbone.Model.extend({ 
    url: 'http://localhost:3000/singIn', 
    defaults: { 
     email:"", 
     password:"" 
    }, 
    signIn: function() { 
     this.save(); 
    } 
}); 
var signInModel = new SignInModel(); 

最後,關於驗證用戶,模型可能不處理這種最好的方式。有幾個關於在骨幹應用中驗證用戶的SO問題,such as this one