CraftyJS 学习二 -- Event

原创
2015/06/24 00:01
阅读数 512

Event 事件系统

Crafty 使用 Event 来完成消息传递。

基本思想就是,为实体绑定事件,然后在其他地方触发事件,事件被立即执行。

// Create a red squarevar square = Crafty.e("2D, Canvas, Color")
        .attr({x:10,y:10, w:30, h:30})
        .color("blue");// When a "Blush" event is triggered, turn pinksquare.bind("Blush", function() {    // the function will be called in the context of the entity
    this.color("pink")
});// Trigger the event, causing the square to turn pinksquare.trigger("Blush");

上面代码中演示了如何绑定代码并立即触发它。

传递数据

例如,我们定义一个 ChangeColor 事件

square.bind("ChangeColor", function(color) {    this.color(color);
});

square.trigger("ChangeColor", "pink"); // Turn pink

当你使用 trigger 方法触发事件时,第二个参数将作为事件的参数传递到对象中。此外,还可以定义更复杂的参数类型,例如:

// Assume that color is an objectsquare.bind("ChangeColor", function(color) {    this.color(color.r, color,g, color.b);
})// Specify the RGB values corresponding to pinksquare.trigger("ChangeColor", {r:255, g:192, b:203});

解绑事件

用绑定事件的引用去解绑事件,所以当需要解绑时,尽量不要使用匿名方法。

var turnPink = function() { 
    this.color("pink");
}// Bind the function to an eventsquare.bind("Blush", turnPink);// Immediately unbind it!square.unbind("Blush", turnPink);

当然,如果你只希望事件被执行一次,可以使用 one 方法替代 trigger。

// Use the .one() method instead of .bind()square.one("JumpRight", function() {    // Move 10 px to the right
    this.x += 100;
});// If we trigger the event twice, the bound function will be called only the first timesquare.trigger("JumpRight");
square.trigger("JumpRight");

使用内置事件

Crafty 内置了很多事件,常用的如 2D 组件中的 “Move” 事件,每当对象的位置发生变化,这个事件都会被触发,事件参数包含了其移动前得位置。

// Bind a function to the "Move" event// It will log the initial and new x position anytime the entity movessquare.bind("Move", function(oldPosition) {    console.log(oldPosition._x, this.x);
});

square.x = 100; // Will print "10, 100"

在 Grafty API 中,绿色高亮部分都是内置 Crafty 事件

全局事件

我们关心的所有的事件都最终被定位到某个具体对象,同时,事件也可以是全局的,触发它会影响到每一个对象。

// Define two entities at x=5 and x=10var varrick = Crafty.e("2D").attr({x:5});var xhuli = Crafty.e("2D").attr({x:10});// Bind to an event called "Thing"varrick.bind("Thing", function() { this.x += 20; });
xhuli.bind("Thing", function() { this.x += 10; });// Do the thing!// varrick and xhuli will *both* move to the rightCrafty.trigger("Thing");// You can still trigger the same events directly on an entityxhuli.trigger("Thing");

我们也可以直接将事件绑定到 Crafty 上。

Crafty.bind("Thing", function() {    console.log("Crafty does the thing.")
});

这个方法的上下文既是 Crafty 对象本身 (this === Crafty)。

Crafty 对象同时也包括了 Crafty.unbind() 和 Crafty.one() 方法。

"EnterFrame" 时 Crafty 中的一个很重要的事件,以后会做重点介绍。





展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
1 收藏
0
分享
返回顶部
顶部