如何添加标签名称为age的文本框并使用backbone.js在模板中查看它?
<label> Age</label>
<input type = "text" name = "age" value="12"/>我想把它作为一个属性添加到模型中,并在模板中查看它。有人能帮上忙吗?我知道backbone.js的基础知识。
发布于 2013-03-06 13:59:18
不确定你想要什么,但这是一个基本的例子:
var App = {};
App.Person = Backbone.Model.extend({});
App.View = Backbone.View.extend({
el: "#form",
render: function() {
var html = _.template($('#form-tpl').html(), this.model.toJSON());
this.$el.html(html);
}
});
$(function() {
var person = new App.Person({
name: 'Thomas',
age: 37
}),
app = new App.View({model: person});
app.render();
});HTML:
<script type="text/template" id="form-tpl">
<label>Age:</label>
<input type="text" name="age" value="<%= age %>">
</script>
<div id="form"></div>http://jsfiddle.net/CX3ud/
此外,还有大量的教程可用。祝好运!
发布于 2013-03-06 14:00:24
模板没有内置到Backbone中,这意味着您必须首先选择一个模板系统。有很多好的选择,但就我个人而言,我更喜欢Handlebars。您还可以选择Mustache、(非常简约的)下划线模板函数、多个jQuery插件等。
一旦你选择了一个库,你通常会用它来构建/编译一个模板函数来生成HTML。下面是一个简单的Handlebar示例:
var template = Handlebars.compile('<span>Hello {{target}}</span>');这可以(可选)作为视图代码的一部分来完成:
var MyView = Backbone.View.extend({
template: Handlebars.compile('<span>Hello {{target}}</span>')
});一旦你有了这个模板函数,你通常会向它传递一个值映射:
var resultText = template({target: 'World!'});并返回渲染结果:
resultText == '<span>Hello World!</span>';您可以根据需要将其添加到Backbone中,但一种常见的模式如下:
var MyView = Backbone.View.extend({
template: Handlebars.compile('<span>Hello {{target}}</span>'),
render: function() {
var valueMap = this.model.toJSON();
this.$el.html(this.template(valueMap));
}
});
// Usage:
new MyView({
el: '#someElement',
model: new Backbone.Model({target: 'World!'}
)).render();https://stackoverflow.com/questions/15239755
复制相似问题