2013-03-15 2 views
0

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); 
    } 

}); 

관련없는 질문은 초기화 기능에서 내 변수를 인스턴스화해야합니까? 나는 아직도 백본에 익숙하지 않고 모범 사례를 찾아 내려고 노력하고있다.

+1

보통 다음 패턴을 사용합니다 :'this.stage.addEventListener ("stagemousedown", _.bind (this.handleMouseDown, this));'밑줄의 bind를 사용합니다 : http://underscorejs.org/#bind – WiredPrairie

답변

2

백본에는 언더 코어 라이브러리가 필요하므로 익숙해지기를 강력히 권장합니다. 많은 장점이 있습니다.

this.stage.addEventListener("stagemousedown", _(function(){ 
    var foo = this.bar; // "this" will be correct now thanks to bind 
}).bind(this); 

을 그것은 또한에 객체의 메소드를 바인딩 (종종 initialize 기능의 내부에) 사용할 수있는 관련 _.bindAll 방법을 가지고, 같은 : 특히 당신이과 같이 사용할 수있는 _.bind 방법이있다 그래서 :

initialize: function() { 
    _(this).bindAll('handleMouseDown'); // handleMouseDown's this will be correct 
    this.stage.addEventListener("stagemousedown", this.handleMouseDown); 
} 

그러나이 모두를 방지하고 당신이 단지의 이벤트 처리를 활용할 경우 백본가 당신을 위해 바인딩 할 수 있도록 할 수 있습니다

Backbone.View.extend({ 
    events: {mousedown: 'handleMouseDown'} 
    handleMouseDown: function() { 
     // this will be bound correctly 
,536,

initialize 안에 변수를 인스턴스화하는 것에 대한 질문은 대답은 ... 아마도 그렇지만 특정 컨텍스트를 알지 못하면 말하기 어렵습니다. 일반적으로 initialize은 콜렉션/모델/뷰가 생성 될 때 발생해야하는 모든 작업을 수행해야하므로 초기화 변수가 그 아래로 떨어지면 확실합니다.

+0

좋은 지적 무; 그에 따라 편집하겠습니다. – machineghost

+0

정확히 내가 뭘 찾고 있었는지, 고마워! – abritez

+0

이것에 대한 유일한 문제는 청취자의 컨텍스트를 뷰의 컨텍스트로 대체한다는 것입니다. – Leonidas