gpt4 book ai didi

javascript - 使用 Marionette 在 CompositeView 中创建 Itemview

转载 作者:行者123 更新时间:2023-11-28 01:48:42 25 4
gpt4 key购买 nike

我正在尝试构建一个应用程序,其中有一个处理鼠标事件的CompositeView,允许您在其中绘制矩形(CompositeView 是矩形的集合)。我正在 CompositeView 内计算/存储矩形所需的所有数据(基本上是宽度、高度、顶部、左侧和边框 css 属性)。

由于我正在计算内容,所以我使用了 itemViewOptions 函数,该函数返回一个包含所有必需数据的对象,这些数据将作为选项传递给我的 ItemView (矩形 View )。

ItemViewinitialize 方法中,我调用 setCssStyle 方法,该方法将 css 属性应用于 View 。

这是我的 CompositeView (ScreenView) 和 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 方法,根据 Marionette Documentation 向其传递 3 个参数:item、ItemViewType、itemViewOptions

问题是我有点困惑,我真的不知道我应该传递的 item 参数是什么。它是 ItemView 的模型吗?我尝试了不同的东西,但不断出错,所以很可能我在这里遗漏了一些基本的东西。

另外,目前我没有 RectangleView 的模型。我应该创建一个吗?如何将 itemViewOptions 从我的 CompositeView 传递到我的 ItemView 并最终传递到模型?

如果我没有很好地解释我的问题,我提前道歉,但我的大脑感觉有点糊状

最佳答案

好吧,我自己解决了这个问题,我想我需要一些 sleep 来清醒头脑!我不知道这是否是最佳解决方案,但它对我有用。

首先,我已经从 CompositeView 切换到 CollectionView,因为我不需要递归性。我还创建了一个空的矩形模型和一个矩形集合。

在我的 App.Initializer 中,当我显示 CollectionView 时,我还将矩形集合传递给它! .show(new ScreenView({collection:矩形}));

现在,您可能还记得,整个交易是能够在 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 属性,因为我的矩形无法就地渲染:/

关于javascript - 使用 Marionette 在 CompositeView 中创建 Itemview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19983668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com