2011-04-08 12 views
11

現在,對於完全不同的東西。backbone.js&raphäel.js/骨幹視圖<->Raphäel對象

當「dom」對象是 raphäel對象時,如何在骨幹視圖中委派事件。這是否有用?像這樣:

var NodeView = Backbone.View.extend({ 
       events: { 
         "click": "click" 
       }, 
       click: function(){ 
         alert('clicked') 
       }, 
       render: function(){ 
         canvas.rect(this.model.get('xPos'), this.model.get('yPos'), 50, 50).attr({ 
          fill: "#EEEEEE", 
          stroke: "none", 
          cursor: "move" 
         }); 
         return this; 
       } 

    }); 

我需要在raphäel對象改變位置時更新模型。當我直接將事件附加到raphäel對象時,我只能訪問該事件,而不是整個視圖,因此不能訪問模型。

回答

4

它應該工作,如果你真的使用DOM元素。例如。如果您有一個Raphael對象圓圈,那麼DOM元素將是circle.node。那個你需要在選項中作爲「el」屬性傳遞,或者確保View的this.el實際上是Raphael對象的「節點」屬性。

如果你想手動綁定事件,並希望能夠訪問在事件處理程序的視圖中,使用下劃線的綁定功能:

$(circle.node).click(_.bind(someHandlerFunction, this)); 

其中應指向視圖對象在當前上下文。在這種情況下,在一些HandlerFunction中,這個對象將成爲視圖。

+0

如果我將Element.node分配給el選項,它將無法正常工作。像這樣:this.el = canvas.rect()然後在事件中分配事件:{}。但是,如果我在render()中手動綁定事件,它就會工作:$(this.el).click(_。bind(function(){this.click()},this)); – thgie 2011-04-08 11:53:05

17

另一種方式做,這是使用新的View.setElement method與參考手動覆蓋在視圖構造函數/初始化的this.el屬性Raphael's Element.node這樣的:

var NodeView = Backbone.View.extend({ 
    initialize: function (args) { 

     // create an empty reference to a Raphael rect element 
     this.element = canvas.rect(); 

     // // overwrite the default this.el by pointing to the DOM object in 
     // // Raphael. This works for older version of backbone.js 
     // this.el = this.element.node; 

     // in backbone 0.9.0+, you are not supposed to override the DOM object 
     // directly. rather, use the new setElement method which also takes 
     // care of the cached this.$el jquery object. 
     this.setElement(this.element.node); 

     // now that we have overwritten the default this.el DOM object, 
     // we need to rebind the events 
     this.delegateEvents(this.events); 
    }, 
    events: { 
     "click": "click" 
    }, 
    click: function(){ 
     alert('clicked'); 
    }, 
    render: function(){ 
     this.element.attr({ 
      x: this.model.get('xPos'), 
      y: this.model.get('yPos'), 
      width: 50, 
      height: 50, 
      fill: "#EEEEEE", 
      stroke: "none", 
      cursor: "move" 
     }); 
     return this; 
    } 
}); 

這裏的好處是,你只需要在一個地方編輯DOM(在渲染函數中),你仍然可以利用Backbone.js的優秀事件處理。我可以通過Raphael 2.0獲得類似的解決方案。雖然我對晚會有點遲,但我想我會發布這個,這樣它可以幫助別人!