Kinetic JS:在向舞台添加图层后是否有回调?

时间:2013-11-19 17:25:40

标签: kineticjs

我有一个循环,我从JSON提要运行。一切都很好。项目在屏幕上,但我想在循环结束后立即运行一些代码。我在循环之后立即放置了代码(在本例中是一个jQuery .map)。它无法识别循环已完成并且我已完成向舞台添加项目。如果我延迟1秒钟,突然发现物品已经装到舞台上。

是否有回调告诉我舞台已准备就绪或我的物品已加载?

我知道必须有一个更好的方法,但这是我脑子里已经烧毁的所有东西。

$.map(jItem, function (jItem1, itemType1) {
    var thisItem = new WordDetails();
    thisItem.id = jItem1.id;
    thisItem.word = jItem1.word;
    thisItem.commentCount = jItem1.commentCount;
    thisItem.journalCount = jItem1.journalCount;
    thisItem.favorite = jItem1.favorite;

    oWords.Randoms[itemType1] = thisItem;

    //Kinetic Setup
    var group = new Kinetic.Group({
        draggable: true,
        width: 149, height: 170,
        x: 100 * itemType1,
        y: 50 * itemType1,
        id: 'word_' + thisItem.word,
        name: 'wordGroup'
    });
    layer = new Kinetic.Layer({ name: 'wordLayer' });

    var imageObj = new Image();
    imageObj.onload = function () {
        var _image = new Kinetic.Image({
            image: imageObj
        });

        var _text = new Kinetic.Text({
            y: 75,
            width: 149,
            text: thisItem.word,
            fontSize: 21,
            fontFamily: 'Arial',
            fontStyle: 'bold',
            fill: '#FFF',
            width: 149,
            align: 'center',
            shadowColor: 'black',
            shadowBlur: 3,
            shadowOffset: [2, 2],
            shadowOpacity: 0.8
        });

        group.add(_image);
        group.add(_text);
        layer.add(group);
        stage.add(layer);

        group.on('dragmove touchmove', function (e) {

        });

        group.on('mouseover', function (e) {
            //verlicon($(this).attr('id'));
        });
    };
    imageObj.src = '/images/leaf_md.png';
});

**//This is the code that needs to run after the loop has completed.**
setTimeout(function () {
    var _children = stage.getChildren();
    var wordGroups = stage.get(".wordGroup");
    for (var i = 0; i < wordGroups.length; i++) {  // for each single shape
        for (var j = 0; j < wordGroups.length; j++) { //check each other shape
            if (i != j) { //skip if shape is the same
                if (checkCollide(wordGroups[i].getX(), wordGroups[i].getY(), wordGroups[j].getX(), wordGroups[j].getY(), wordGroups[j].getWidth(), wordGroups[j].getHeight()))
                    alert('top left corner collided');
            }
        }
    }
}, 1000);

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

Kinetic允许您触发自定义事件,所以......

// after your loop code, fire a custom event

stage.fire("iamdoneloading");

// and respond by doing your time-sensitive code

stage.on("iamdoneloading",function(){

    var _children = stage.getChildren();

    ...  

}