Help
@fabienallouis - twitter @allouis - github
API
on
: Listen to event. Params { type:String
, callback:Function
| context:Object
}
off
: Stop listening to event. Params { type:String
| callback:Function
}
emit
: Emit event. Params { type:String
| data:Object
}
trigger
is no longer supported!!
:%s/myobj.trigger(/myobj.emit(/
should do the trick in VIM
Examples
Basic
var sandbox = new Events
sandbox.on("event", function(){
// do stuff
})
sandbox.emit("event") //does stuff
sandbox.off("event")
sandbox.emit("event") //does not do stuff
Mixin
var sandbox = {
otherStuff: true
}
Events(sandbox)
sandbox.on("event", function(){
// do stuff
})
Using Context
var sandbox = new Events
var obj = {
name: "fabien"
}
function sayName(){
console.log(this.name);
}
sandbox.on("event", sayName)
sandbox.emit("event") // undefined
//stop listening to original event, we go it wrong
sandbox.off("event")
//pass in context of 'this'
sandbox.on("event", sayName, obj)
sandbox.emit("event") // fabien
Using Off
var sandbox = new Events
function doStuff(){
// do stuff
}
sandbox.on("event", function(){
alert("event happened")
})
sandbox.on("event", doStuff)
sandbox.emit("event") //event happened && does stuff
// remove just this callback
sandbox.off("event", doStuff)
sandbox.emit("event") // event happened
// re-add listener to show can remove all at once
sandbox.on("event", doStuff)
// remove all
sandbox.off("event")
sandbox.emit("event") // nothing...
Passing Parameters
var sandbox = new Events
sandbox.on("event", function(obj, arr, num, bool){
console.log(obj.name)
console.log(arr)
console.log("5 + " + num + " = " + (5+num))
if(bool) console.log("It's true!!");
})
sandbox.emit("event", {name: "fabien"}, [1,2,3], 7, false)
// fabien, [1,2,3], 5 + 7 = 12