Crafty 使用 Event 来完成消息传递。this
基本思想就是,为实体绑定事件,而后在其余地方触发事件,事件被当即执行。spa
// 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");
上面代码中演示了如何绑定代码并当即触发它。code
传递数据orm
例如,咱们定义一个 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});
用绑定事件的引用去解绑事件,因此当须要解绑时,尽可能不要使用匿名方法。ci
var turnPink = function() { this.color("pink"); }// Bind the function to an eventsquare.bind("Blush", turnPink);// Immediately unbind it!square.unbind("Blush", turnPink);
固然,若是你只但愿事件被执行一次,可使用 one 方法替代 trigger。it
// 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” 事件,每当对象的位置发生变化,这个事件都会被触发,事件参数包含了其移动前得位置。io
// 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 事件console
咱们关心的全部的事件都最终被定位到某个具体对象,同时,事件也能够是全局的,触发它会影响到每个对象。
// 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 中的一个很重要的事件,之后会作重点介绍。