Backbone 视图对象主要用来渲染数据,监听事件。
Backbone的视图对象可以展示Model数据,也可以把用户编辑的Model数据传递到后台,可以通过监听事件操作视图里的DOM元素
举例:
var PreviewInvoiceItemView=Backbone.View.extend({ el:'#itemList', template: _.template($('#InvoiceItem').html()), initialize:function(){ this.template= _.template($('#InvoiceItem').html()); }, events:{ 'click .delete':'dele', 'click .pluc':'show' }, render:function(){ var that=this; items.each(function(model){ var data={}; data.price=model.get('price'); data.quantity=model.get('quantity'); data.amount=model.calculateAmount(); data.cid=model.cid; that.$el.append(that.template(data)); }); return this; }, dele:function(event){ items.remove(items.get($(event.target).attr('cid'))); }, show:function(){ //var s= items.some(function(model){ // return model.get('price')<3; // }); // this.$('#pluc').html(s.toString()); var ti=items.create({price:100,quantity:200}); } });
extend "layout" block 'content',-> div ->'nihao' div id:'itemList',-> div id:'pluc',-> script id:"InvoiceItem",type:"text/template",style:"display: none",-> div style:'border:1px solid #ddd;height:40px;',-> div style:'float:left;',->"{{price}}" div style:'float:left;margin-left:20px;',->"{{quantity}}" div style:'float:left;margin-left:20px;',->"{{amount}}" button class:'delete',style:'float:left;margin-left:20px;',cid:'{{cid}}',->"删除" coffeescript -> $ -> new PreviewInvoiceItemView().render()