当前位置: 首页 > 工具软件 > Backbone.js > 使用案例 >

backbone.js初使用

聂迪
2023-12-01

中文网地址: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();

 类似资料: