如何添加带有标签名称年龄的文本框并使用backbone.js在模板中查看它?
<label> Age</label>
<input type = "text" name = "age" value="12"/>
我希望将此作为属性添加到模型并在模板中查看。任何人都可以帮忙吗?我知道backbone.js 的基础知识。
如何添加带有标签名称年龄的文本框并使用backbone.js在模板中查看它?
<label> Age</label>
<input type = "text" name = "age" value="12"/>
我希望将此作为属性添加到模型并在模板中查看。任何人都可以帮忙吗?我知道backbone.js 的基础知识。
不确定你想要什么,但这里是基本示例:
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>
还有大量可用的教程。祝你好运!
Templating isn't built-in to Backbone, which means you first have to pick a templating system. There are many good options out there, but personally I prefer Handlebars. You could also choose from Mustache, the (very minimalist) Underscore template function, multiple jQuery plug-ins, etc.
Once you pick a library, you'll generally build/compile a template function with it to generate the HTML. Here's a simple Handlebars example:
var template = Handlebars.compile('<span>Hello {{target}}</span>');
That can (optionally) be done as part of your View code:
var MyView = Backbone.View.extend({
template: Handlebars.compile('<span>Hello {{target}}</span>')
});
Once you have that template function, you typically pass it a value map:
var resultText = template({target: 'World!'});
and get back the rendered result:
resultText == '<span>Hello World!</span>';
You can fit that in to Backbone however you want, but one common pattern is something like the following:
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();