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は、オンデマンドでテンプレートをフェッチして配列に格納し、メモリから2回目の要求があった場合に同じテンプレートを送り返す、単なるjavascriptコードです(ここでコードを取得しました)
しかし、このように表示されます:
(サーバーから返されるテキストボックスの値を参照してください)
私を助けてください、これは本当に奇妙です.................。
:(
これはサーバー(テンプレート)から来ている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>