backbone.js初使用

中文网地址:https://www.backbonejs.com.cn/

demo案例:

var song = Backbone.Model.extend();
var SongView = Backbone.Model.extend({
	render:function(){
		this.$el.html(this.model.get("title"))
		return this;
	}
});

var song = new Song({
	title:"Blue in Green"
});
var songView = new SongView({
	el:"#container",
	model:song;
});
songView.render();



===========================================================
var Songs = Backbone.Collection.extend({
	model:song
})
var songs = new Songs({
	new Song({id:'1',title:"Blue in Green"})
	new Song({id:'2',title:"So What"})
	new Song({id:'3',title:"All Blues"})
})
//定义
var SongsView = Backbone.View.extend({
	initalize:function(){
		this.model.on("add",this.onSongAdded,this); //监听到执行了add方法,就调用onSongAdded这个方法;【this.model是Songs  == songs.add(new Song({title:'new Song'}))】
		this.model.on("remove",this.onRemoved,this);
	},
	onSongAdded:function(song){
		console.log('song added!')
		this.$el.append(songView.render.$el);
	},
	onRemoved:function(song){
		this.$el.find("li#"+song.id).remove();
	},
	render:function(){
		this.model.each(function(song){
			var songView = new SongView({model:song})
			this.$el.append(songView.render().$el);
		})
	}
})
//初始化
var SongsView = new SongsView({
	el:"#container",
	model:songs,
});
//调用
songsView.render();

=========================================================================================
<script id="songTemplate" type="text/html">
	<%=title%>  //此处实际上就是个占位符,类似于vue中的{{title}}
	<button>Listen</button>
	<%if (plays > 1000) {%>                       //和jsp语法差不多
		<span class="popular">Popular</span>
	<%}%>
</script>
var Song = Backbone.Model.extend({});
var SongView = Backbone.Model.extend({
	render:function(){
		var template = _.template($("#songTemplate").html());
		var html = template(this.model.toJSON());
		this.$el.html(html);
		return this;
	}
})
var song = new SongView({title:"Blue in Green",plays:10});
var songView = new SongView({
	el:"#container",
	model:song,
});
songView.render();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值