ちょっとはまったのでメモ。
こんな感じで別ファイル定義のViewの中で、elの定義に$(“#id”)なjQueryオブジェクトを使うと、うまく動きませんでした。
var MyView = Backbone.View.extend({ el : $("#id"), ... });
どうしてダメかは何となくはわかりますが、ちゃんと調べてないです。
回避策
- jQueryオブジェクトではなく、セレクターを使う。
- Viewをインスタンスを作成するときにjQueryオブジェクトを渡す。
サンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html xmlns="http://www.w3.org/1999/xhtml"> | |
<head> | |
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> | |
<title></title> | |
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.js"></script> | |
<script type="text/javascript" src="underscore-1.4.3.js"></script> | |
<script type="text/javascript" src="backbone-0.9.9.js"></script> | |
<script type="text/javascript" src="hoge.js"></script> | |
<script type="text/javascript" src="foo.js"></script> | |
<script type="text/javascript" src="bar.js"></script> | |
<script type="text/javascript"> | |
$(document).ready(function () { | |
new Hoge({}); | |
new Foo({}); | |
new Bar({ el: $("#bar") }); | |
}); | |
</script> | |
</head> | |
<body> | |
<div id="hoge"></div> | |
<div id="foo"></div> | |
<div id="bar"></div> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <reference path="http://code.jquery.com/jquery-1.8.3.js"/> | |
/// <reference path="backbone-0.9.9.js" /> | |
var Hoge = Backbone.View.extend({ | |
el : $("#hoge"), | |
initialize: function(){ | |
this.render(); | |
}, | |
render : function(){ | |
this.$el.text("hoge"); | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <reference path="http://code.jquery.com/jquery-1.8.3.js"/> | |
/// <reference path="backbone-0.9.9.js" /> | |
var Foo = Backbone.View.extend({ | |
el : "#foo", | |
initialize: function(){ | |
this.render(); | |
}, | |
render : function(){ | |
this.$el.text("foo"); | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <reference path="http://code.jquery.com/jquery-1.8.3.js"/> | |
/// <reference path="backbone-0.9.9.js" /> | |
var Bar = Backbone.View.extend({ | |
initialize: function(){ | |
this.render(); | |
}, | |
render : function(){ | |
this.$el.text("bar"); | |
} | |
}); |