backbone入门系列(3)视图

继续用extend

Backbone.View.extend(properties, [classProperties]) 

1.var NoteView = Backbone.View.extend({})视图默认含有el元素,内容为div

2.在括号里可以设置元素内容和各种属性

var noteView = Backbone.View.extend({
tagName: 'li',  // 将div改为li
className: 'item',  //设置class为item
attributes: {
'data-role': 'list'     //其他属性
}
});

3.再介绍一个方法,渲染render

代码

/**
* 模型 - 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';
}
}
});

/**
* 视图 - View
*/

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>

继续执行

原文地址:https://www.cnblogs.com/cumting/p/6854983.html