【发布时间】:2014-10-15 19:35:29
【问题描述】:
是否可以从一个backbone.js 视图渲染一个带有未在相关Backbone.js 模型中定义的变量的underscore.js 模板?
采取can't find variable: username 错误。
要渲染的模板:
<div class="content" id="content">
<div id="form">
<form action="">
<input id="username" type="text" placeholder="Username" name="username" value= <%=username%> >
<input id="password" type="password" placeholder="Password" name="password" >
<ul class="table-view">
<li class="table-view-cell">
Remember me
<div class="toggle active">
<div class="toggle-handle"></div>
</div>
</li>
</ul>
<button id="logbtn" class="btn btn-primary btn-block">Login</button>
</form>
<button id="renregbtn" class="btn btn-positive btn-block">Register</button>
</div>
</div>
视图中的渲染线:
this.$el.html( this.template_login( this.loginModel ) );
loginModel 模型文件中的一行:
define([
'underscore',
'backbone',
],
function(_, Backbone) {
var LoginModel = Backbone.Model.extend({
urlRoot: '/login',
initialize: function(){
this.fetch();
},
});
return LoginModel;
});
我手动设置模型。但仍然像第一个渲染案例一样出现找不到变量错误。
以上同款:
define([
'underscore',
'backbone',
],
function(_, Backbone) {
var LoginModel = Backbone.Model.extend({
urlRoot: '/login',
defaults: {
username: "abc",
},
initialize: function(){
this.fetch();
},
});
return LoginModel;
});
两种情况都会导致:
ReferenceError: Can't find variable: username
只有当我将硬编码的模型 json 输入到 template_login 时它才能工作。
this.$el.html( this.template_login( {username: "Joe"} ) );
【问题讨论】:
标签: javascript backbone.js underscore.js