[英]Template is not working in Backbone.js
我剛剛開始在Backbone.js中工作
在那我創建了一個簡單的示例,使用underscore.js顯示模板中的值
現在,我想創建一些高級示例,以使用模型對象在模板中顯示用戶的值
現在我的模型是(EditProfileModel.js):
window.EditProfileModel = Backbone.Model.extend({
constructor : function(attributes, options) {
Backbone.Model.apply(this, arguments);
},
defaults : {
id : '',
firstName : '',
lastName : '',
},
urlRoot: 'rest/editProfile'
});
EditProfileView.js:
window.EditProfileView = Backbone.View.extend({
template : 'tpl/EditProfileTpl.html',
el: content,
initialize:function () {
this.render();
},
events: {
},
render:function () {
var $this = this;
var editProfileModel = new EditProfileModel({
id:this.model.get('id')
});
//GET editProfile/id
editProfileModel.fetch({
success : function(model){
//console.log("I am fetch " + JSON.stringify(model));
TemplateManager.get($this.template, function(template){
console.log($(template).html());
var html = _.template($(template).html(),{user : model});
$this.$el.html(html);
return $this;
});
}
});
},
});
和main.js與路由器的事情是:
.....
routes : {
"profile/:id" : "editProfile"
},
editProfile : function(id){
var $this = this;
$this.model = new EditProfileModel({
id:id
});
$('#content').html(
new EditProfileView({
model: $this.model
})
);
}
......
TemplateManager只是一個JavaScript代碼,可按需獲取模板並將其存儲在數組中,如果第二次從其內存中請求再次發送相同的模板。(我在這里獲得了代碼)
但其顯示如下:
(請參閱文本框值,因為它是從服務器返回的,因此應為admin )
請幫助我,這真的很奇怪.........
:(
這是來自服務器(模板)的html :::
<div>
<form id="frmEditProfile" class="form-horizontal">
<div class="control-group">
<label class="control-label" for="firstName">FirstName</label>
<div class="controls">
<input id="firstName" name="firstName" placeholder="firstName" value="<%=model.get('firstName')%>" autofocus="autofocus">
</div>
</div>
<div class="control-group">
<label class="control-label" for="lastName">LastName</label>
<div class="controls">
<input type="text" id="lastName" name="lastName" placeholder="lastName">
</div>
</div>
<input type="hidden" name="id" value="">
<div class="control-group">
<div class="controls">
<button class="btn btn-primary" id="btnSave" type="submit">
<i class="icon-ok"></i> Save
</button>
</div>
</div>
</form>
</div>
TemplateManager? 您是否看到在您發布的鏈接中Derrick提到這是一個壞主意?
無論如何:您記錄了$ template.html(),只需要記錄模型,那么您應該能夠在控制台中看到問題所在。
嘗試解碼從TemplateManager
返回的HTML實體。
var data = model.toJSON();
var tmpl = $("<div />").html($(template).html()).text();
var html = _.template(tmpl, {firstName: data.firstName});
還要將模板更改為此:
<input id="firstName" name="firstName" placeholder="firstName"
value="<%= firstName %>" autofocus="autofocus">...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.