Backbonejsビュー内でEaseljsを使用して作成された単純な描画ビューを取得しているところです。リスナーイベントで、スコープに問題があります。たとえば、次のようになります。
this.stage.addEventListener("stagemousedown", this.handleMouseDown);
スコープの問題を回避するためにこれを始めました
var self = this;
this.stage.addEventListener("stagemousedown", function(){
var foo = self.bar;
});
ただし、特に移植しているサンプルコード(http://www.createjs.com/#!/EaselJS/demos/drawing)にはネストされたレベルのeventListenersがあるため、これはお粗末なようです。
SketchView = Backbone.View.extend({
initialize: function(){
this.canvas;
this.stage;
this.drawingCanvas;
this.oldPt;
this.oldMidPt;
this.title;
this.color;
this.stroke;
this.colors;
this.index;
},
beforeRender : function (){
this.template = _.template( tpl.get(this.templateFile) );
},
render: function(eventName) {
$(this.el).html(this.template(this.model));
return this;
},
//add in UI
afterRender : function (){
this.createUI();
},
createUI: function() {
this.canvas = document.getElementById("demoCanvas");
this.index = 0;
this.colors = ["#828b20", "#b0ac31", "#cbc53d", "#fad779", "#f9e4ad", "#faf2db", "#563512", "#9b4a0b", "#d36600", "#fe8a00", "#f9a71f"];
//Create a stage by getting a reference to the canvas
this.stage = new createjs.Stage(this.canvas);
this.stage.autoClear = false;
this.stage.enableDOMEvents(true);
createjs.Touch.enable(this.stage);
createjs.Ticker.setFPS(24);
this.stage.addEventListener("stagemousedown", this.handleMouseDown);
this.stage.addEventListener("stagemouseup", this.handleMouseUp);
this.title = new createjs.Text("Click and Drag to draw", "36px Arial", "#777777");
this.title.x = 300;
this.title.y = 200;
this.stage.addChild(this.title);
this.stage.addChild(this.drawingCanvas);
this.stage.update();
},
handleMouseDown: function (event) {
if (this.stage.contains(this.title)) { this.stage.clear(); this.stage.removeChild(this.title); }
this.color = this.colors[(this.index++)%this.colors.length];
this.stroke = Math.random()*30 + 10 | 0;
this.oldPt = new createjs.Point(this.stage.mouseX, this.stage.mouseY);
this.oldMidPt = this.oldPt;
this.stage.addEventListener("stagemousemove" , this.handleMouseMove);
},
handleMouseMove: function (event) {
var midPt = new createjs.Point(this.oldPt.x + this.stage.mouseX>>1, this.oldPt.y+this.stage.mouseY>>1);
this.drawingCanvas.graphics.clear().setStrokeStyle(this.stroke, 'round', 'round').beginStroke(this.color).moveTo(midPt.x, midPt.y).curveTo(this.oldPt.x, this.oldPt.y, this.oldMidPt.x, this.oldMidPt.y);
this.oldPt.x = this.stage.mouseX;
this.oldPt.y = this.stage.mouseY;
this.oldMidPt.x = midPt.x;
this.oldMidPt.y = midPt.y;
this.stage.update();
},
handleMouseUp: function (event) {
this.stage.removeEventListener("stagemousemove" , this.handleMouseMove);
}
});
無関係な質問ですが、初期化関数で変数をインスタンス化する必要がありますか?私はまだBackboneを初めて使用し、ベストプラクティスを理解しようとしています。