所以我一直在用 Javascript 开发一个项目,该项目接收用户提供的对象并用 HTML 表示它们。现在,它们在内存中表示为数组,在显示中表示为单独的数组。集成一些代码更改后,出现了问题,因为显示数组似乎无法删除其内容,因此应该删除的内容不会从 View 中消失。
声明列表:
this.divList = gDocument.getElementById( element );
this.objectList = [];
将对象添加到列表中:
addObject = function (address, type){
var newDiv = gDocument.createElement("div");
this.divList.appendChild( newDiv );
var d = this.createObject( newDiv, address, type );
if (undefined != d)
{
this.objectList.push(d);
}
}
divList 准确地反射(reflect)了 objectList,直到在运行时对 objectList 进行了任何更改。重新启动后,列表将再次同步。当我尝试修复它时,事情变得非常复杂。我想知道是否有更好的方法来设计这样的想法(对象模型和图形表示)。任何评论都会有帮助,谢谢。
最佳答案
抛开问题的模糊性不谈,我的建议是在内存中存储一个列表,而不是两个。每个列表元素都是一个对象,其中包含该特定抽象“对象”所需的所有必要数据(“用户提供的”数据)。像这样的事情:
this.divList = gDocument.getElementById(element);
this.masterList = [];
var i,
len = this.divList.length;
for (i = 0; i<len; i++)
{
this.masterList.push({
elt: this.divList[i],
obj: /* however you'd create the object in this.objectList */
});
}
<小时/>
编辑:您的 addObject
函数将更改为如下所示:
addObject = function (address, type)
{
var newDiv = gDocument.createElement("div"),
newObj = {elt: newDiv,
obj: this.createObject(newDiv, address, type)};
this.masterList.push(newObj);
this.divList.appendChild(newDiv);
}
您应该存储对要 appendChild()
的 HTML 元素的引用。您已经这样做了 - 但是当您需要操作各个元素(例如删除一个元素)时,请使用 masterList
来代替:
removeObject = function (i)
{
var toRemove = this.masterList.splice(i, 1);
if (toRemove)
{
this.divList.removeChild(toRemove.elt);
}
}
另请参阅Array.splice()
.
关于Javascript和HTML数据模型和表示模型设计问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4616228/