2014-02-28 136 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