简体   繁体   中英

KineticJS .on() not working on cloned shape

I'm making an editable pattern that users can use and reuse to make a larger pattern. When users drag the first small pattern into the large pattern grid, I clone it, add it to another layer and let users reuse or edit it. The cloned node is still editable and draggable, but the bound events are not firing with interaction. Here's my code:

 var B = A = new Kinetic.Shape();
 var stage = new Kinetic.Stage({
    container: 'container',
    width: 1000,
    height: 650
  });
 var Alayer = new Kinetic.Layer();
 var Blayer = new Kinetic.Layer();

 var BGrid = new Kinetic.Group();

for(var v = 0; v < 4; v++){
for(var h = 0; h < 4; h++){
    (function(){
        var grid = new Kinetic.Rect({
            x: 300 + (h * 120),
            y: 50 + (v *120),
            width: 120,
            height: 120,
            stroke: 'black',
            strokeWidth: 1,
            listening: false
        });
        BGrid.add(grid);
    })();  
 }

}

(function() {
  var AS = new Kinetic.Rect({
    x: 150,
    y: 110,
    width: 120,
    height: 120,
    draggable:true,
    stroke: 'black',
    strokeWidth: 1,
    offset: [60,60],
    });
B = AS;
Alayer.add(B);
})();

Blayer.add(BGrid);


stage.add(Blayer);
stage.add(Alayer);

Blayer.on('click', function(evt) {
 B = evt.targetNode;
 B.setStroke('red');

});
B.on('dragend',function(){
   var px = B.getX();
   var py = B.getY();
//some code that's not executing
});
A.on('dragend',function(){
var sx = A.getX();
var sy = A.getY();
if((300 < sx && sx < 780) && (50 < sy && sy < 530)){
    A.moveTo(Blayer);
    B = A;
    var C = A.clone();
    C.setPosition(150,110);
    Alayer.add(C);
    A = C;
}else{
    A.setPosition(150,110);
}
Alayer.draw();
Blayer.draw();
});

I'd really appreciate any help with this.

You have typo:

B.on('dragend',function(){
  var px = B.getX();
  var py = B.getY();   // not b.getY();
  alert("dragend!");
  //some code that's executing
});

http://jsfiddle.net/lavrton/JYqJp/

Here's the solution I came up with, not sure if it'll help anyone, but I hope it does.

stage.on('dragend',function(e){
var t = e.targetNode;
var n = t.getName();
var sx = t.getAbsolutePosition().x;

if(300 < sx && sx < 780 && n == 'A'){

    //previous code for A

}else if(300 < sx && sx < 780 && n != 'A'){

    //previous code for B

}else if(n == 'A'){

    t.setAbsolutePosition(150,110);

}else{

    t.remove();
}
stage.draw();
});`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM