2013-11-14 34 views
1

我試圖構建一個應用程序,其中有一個處理鼠標事件的CompositeView,允許您在其中繪製矩形(CompositeView是矩形的集合)。我正在計算/存儲CompositeView內的矩形(基本上是寬度,高度,頂部,左側和邊框CSS屬性)所需的所有數據。我使用了itemViewOptions函數,它返回一個包含所有必要數據的對象,它將作爲選項傳遞給我的ItemView(RectangleView)。在CompositeView中使用Marionette創建一個ItemView

ItemViewinitialize方法中,我調用setCssStyle方法,該方法將css屬性應用於視圖。

這裏是我的CompositeView中的(屏幕視圖)和ItemView控件(RectangleView)

var RectangleView = Backbone.Marionette.ItemView.extend({ 
    template: "<div>I am a rectangle</div>", 
    className: "rectangle", 

    initialize: function(options){ 
    this.left = options.left; 
    this.top = options.top; 
    this.width = options.width; 
    this.height = options.height; 
    this.border = options.border; 
    this.setCssStyle(); 
    }, 
    setCssStyle: function() { 
    this.$el.css({ 
     'width': this.width + 'px', 
     'height': this.height + 'px', 
     'top': this.top + 'px', 
     'left': this.left + 'px', 
     'border': this.border 
    }); 
    } 
}); 


var ScreenView = Backbone.Marionette.CompositeView.extend({ 
    template: "<div> </div>", 
    className:"screen", 
    itemView: RectangleView, 

    itemViewOptions: function() { 
    return { 
     left: this.left, 
     top: this.top, 
     width: this.width, 
     height: this.height, 
     border: this.border 
    } 
    }, 

[...] 

}); 

我讀過,我需要重寫buildItemView方法傳遞3個參數代碼(中省略爲簡潔的計算和數據stopring方法) :item, ItemViewType, itemViewOptions根據Marionette Documentation

問題是,我有點困惑,我真的不知道什麼是item參數我應該通過。它是ItemView的模型嗎?我嘗試了不同的東西,並不斷得到錯誤,所以很可能我錯過了一些基本的東西。

此外,目前我沒有爲我的RectangleView模型。我應該創建一個嗎?如何將itemViewOptions從我的CompositeView傳遞到我的ItemView並最終傳遞給模型?

我提前道歉,如果我沒有解釋我的問題很好,但我的大腦感覺有點肉麻

回答

1

好,我設法弄清楚這一點對我自己,我想我需要一些SLEP清除我的頭!我不知道這是否是最佳解決方案,但它適用於我。

首先,我已經從CompositeView切換到CollectionView,因爲我不需要遞歸。我還創建了一個空的Rectangle模型和一個Rectangles集合。

在我的App.Initializer中,當我顯示CollectionView時,我也將矩形集合傳遞給它! .show(new ScreenView({collection: rectangles}));

現在,你可能還記得,整個交易是能夠繪製的CollectionView內的矩形,在的CollectionView內繪製矩形將集合中的添加(每個將有一個模型等等...)

把這些代碼的理想地點是在我的我的CollectionView內mouseup事件(想想,你點擊 - >拖 - >鬆開鼠標按鈕來繪製一個框)一旦

[...] 
    handleMouseUp: function(e) { 
    [...] 
    if (this.dragging===1) { 

     //passing the itemViewOptions on a helper 
     var modelHelper = this.itemViewOptions(); 

     //instantiating Rectangle by passing it the itemViewOptions 
     var rectangle = new Rectangle (modelHelper); 

     //adding newly instantiated rectangle in the collection 
     this.collection.add(rectangle); 
     console.log(this.collection); 
    } 
    }, 

當您在集合中添加矩形時,CollectionView將負責渲染它! :)

請讓我知道是否有任何優化或其他方式做到這一點!現在我必須照顧CSS的屬性,因爲我的矩形不會渲染到位:/

相關問題