继续用extendjavascript
Backbone.View.extend(properties, [classProperties]) html
1.var NoteView = Backbone.View.extend({})视图默认含有el元素,内容为divjava
2.在括号里能够设置元素内容和各类属性node
如jquery
var noteView = Backbone.View.extend({
tagName: 'li', // 将div改成li
className: 'item', //设置class为item
attributes: {
'data-role': 'list' //其余属性
}
});浏览器
3.再介绍一个方法,渲染renderthis
代码spa
/**
* 模型 - Model
*/
var Note = Backbone.Model.extend({
defaults: {
title: '',
created_at: new Date()
},
initialize: function() {
console.log('新建立了一条笔记:' + this.get('title'));
this.on('change', function(model, options) {
console.log('属性的值发生了变化');
});
this.on('change:title', function(model, options) {
console.log('title 属性发生了变化');
});
this.on('invalid', function(model, error) {
console.log(error);
})
},
validate: function(attributes, options) {
if (attributes.title.length < 3) {
return '笔记的标题字符数要大于 3';
}
}
});3d
/**
* 视图 - View
*/htm
var NoteView = Backbone.View.extend({
tagName: 'li',
className: 'item',
attributes: {
'data-role': 'list'
},
render: function() {//要利用模型的各个属性,要定义render方法
this.$el.html(this.model.get('title'));//$el返回jquery对象
}
});
var note = new Note({
title: '西红柿炒鸡蛋的作法' //实例化一个模型
});
var noteView = new NoteView({ //实例化一个视图,而且利用note模型
model: note
});
执行状况
先执行一下render方法
4.模板功能
backbone自己不带这个功能,可是能够利用underscore的模板功能
接下来为noteView这个视图准备一个模板
第一步要在html文档定义模板
<script type='text/template' id='list-template'> //type属性表示模板,以避免被误觉得javascript文档
<span> <%=title %> <small class="pull-right"><%=time %></small> </span>//输出模型里属性的值
</script>
第二步在nodeview中加语句
template: _.template(jQuery('#list-template').html()),//下划线指underscore
改造render方法:
render: function() {
this.$el.html(this.template(this.model.attributes));
}
在浏览器执行
通过检查,前面模板写错了,没有找到time这个属性,正确的应该为
<script type='text/template' id='list-template'>
<span> <%=title %> <small class="pull-right"><%=created_at %></small> </span> //把time改成created_at
</script>
继续执行