8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Backbone.js事始め その2

Last updated at Posted at 2014-09-18

ソースコード

前回の記事に、さらにViewを追加してみた。
ソースコードは長く感じるが、簡単なことしかやってない。

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

	<title>こんにちは。動物さん</title>

	<!-- テンプレート作成 -->
	<script type="text/template" id="animal-template">
		<div>
			こんにちは<b><%- name %>ちゃん</b>(<%- species %>)
		</div>
	</script>

	<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
	<script type="text/javascript" src="http://underscorejs.org/underscore-min.js"></script>
	<script type="text/javascript" src="http://backbonejs.org/backbone-min.js"></script>
</head>
<body>
	<h3>こんにちは。動物さん。</h3>
	<div id="myList"></div>

	<script type="text/javascript">
	(function() {
		//----------
		// Model作成
		//----------
		var Animal = Backbone.Model.extend({
			//Attribute(属性)
			defaults: {
				species: "Animal",
				name: "None"
			},
			//コンストラクタ
			initialize: function(){
				console.log("初期化処理 : " + this.get("species"));
			},
			//メソッド
			call: function(){
				console.log("動物 : " + this.get("species"));
				console.log("私の名前は" + this.get("name") + "です。");
			}
		});
		//Animalのインスタンス化	
		var none = new Animal();

		//Animal(犬)のインスタンス化	
		var dog = new Animal({
			species: "",
			name: "ポチ"
		});
		//Animal(猫)のインスタンス化	
		var cat = new Animal({
			species: "",
			name: "タマ"
		});

		//----------
		// View作成
		//----------
		var BaseView = Backbone.View.extend({
			tagName: "div",
			//id: "myDivId",
			className: "myDivClass",
			//テンプレート作成
			template: _.template($('#animal-template').html()),
			render: function(){
				this.$el.html(this.template(this.model.toJSON()));
				return this;
			},
			//イベント定義
			events: {
				"click": "call"
			},
			//イベント実装
			call: function(){
				this.model.call();
				//alert(this.model.get("name"));
			}
		});
		var dogDiv = new BaseView({model: dog});
		var catDiv = new BaseView({model: cat});
		$('#myList').append(dogDiv.render().el);
		$('#myList').append(catDiv.render().el);

	})();
	</script>
</body>
</html>

実行結果

ブラウザ上の文字をクリックすると、Modelに実装したメソッドが実行され、コンソールに結果が表示される。

スクリーンショット 2014-09-18 15.27.51.png

8
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?