从自身的一个版本中创建新的JavaScript对象

create new javascript object from within a version of itself

本文关键字:版本 创建 JavaScript 一个 对象      更新时间:2023-09-26

我从这篇博文中分叉了一个JSfiddle(只是为了在星期二晚上好玩......http://boundary.com/blog/2012/07/03/building-node-diagrams-in-html5/

并且每次双击一个时都试图创建一个链接new Node()。我的小提琴在这里http://jsfiddle.net/joevallender/cGzCe/4/

起初我试图不弄乱库,但小提琴包括(在资源中(一个更改版本,我在其中添加了对 dblclick 事件的支持。

无论如何,切中要害!我正在传递一个要在事件上运行的函数,双击firstNode时它确实有效,但我需要不断将事件重新添加到每个新创建的节点/以某种方式引用创建函数,这会猜测我们进入循环。

var create = function() {
  var node = new Node({
    title: 'Node',
    stage: stage,
    w: NODE_DIMENSIONS.w,
    h: NODE_DIMENSIONS.h,
    x: 100,
    y: 100
  }).attach();
  new Segment({
    h: 5,
    stage: stage,
    origin: this,
    destination: node
  }).attach();
}
var firstNode = new Node({
    title: 'Node',
    stage: stage,
    w: NODE_DIMENSIONS.w,
    h: NODE_DIMENSIONS.h,
    x: 350,
    y: 50,
    events: {
        dblclick: create
    }
}).attach();

我觉得我应该考虑修改双击事件的原型功能,但只是有点迷路了。有没有人知道我在说什么?b(你能帮忙吗?这不是客户工作或任何东西,但我只是想知道!

我已经快速扫描了重复的内容,但正如您可能从我措辞糟糕的问题标题中可以看出的那样,我不完全确定如何措辞我的搜索!

实现此目的的最快方法是将dblclick事件添加到创建的节点。您应该能够扩展 Node 类以自动执行此操作,但我不确定是否有必要。

var create = function() {
  var node = new Node({
    title: 'Node',
    stage: stage,
    w: NODE_DIMENSIONS.w,
    h: NODE_DIMENSIONS.h,
    x: 100,
    y: 100,
    events:{ // add the event to the created node. 
      dblclick: create
    }
  }).attach();
  new Segment({
    h: 5,
    stage: stage,
    origin: this,
    destination: node
  }).attach();
  //nodes.push(node);
}

为了定位新创建的节点,我建议它相对于它们产生的节点:

var create = function() {
  var ancestor = $(event.target); // get the element that was double clicked
  var top = ancestor.position().top;  // and its position
  var left = ancestor.position().left;
  var node = new Node({
    title: 'Node',
    stage: stage,
    w: NODE_DIMENSIONS.w,
    h: NODE_DIMENSIONS.h,
    x: left + 100,        //new position relative to the parent.
    y: top + 100,
    events:{
      dblclick: create
    }
  }).attach();
  new Segment({
    h: 5,
    stage: stage,
    origin: this,
    destination: node
  }).attach();
  //nodes.push(node);
}

您的代码工作正常,但问题是新节点相互重叠,因为在创建函数中,您的 x 和 y 位于 100 以创建新节点。

所以我使用 math.random 为新节点生成随机的 x,y 位置

这是演示

您应该根据需要随机生成新的节点位置和名称