Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to expose events from JavaScript custom objects

I have a custom object in JavaScript:

function Graph (dataType, provider){
   this.dataType = dataType;
   this.provider = provider;
}

I instantiate this object via "new" and then pass it to other parts of my code that may need to keep track of changes to this object's properties.

When the properties of the Graph object are modified, I want all other consumers of that object to be notified. In languages like C# I would have a setter in which I would raise an event. What is a proper way to create events in custom JavaScript objects?

like image 842
user1044169 Avatar asked Oct 06 '22 18:10

user1044169


1 Answers

Using JQuery, you can create and also attach events of any type to whatever object you want, at any time.

function Graph (dataType, provider){
   this.dataType = dataType;
   this.provider = provider;
}

var g = new Graph;

g.dataType = "whatever1";
g.provider = "whatever2";
g.event = $.Event("mywhateverEvent");
g.myOwnProperty2 = $.Event("thisisAnEventToo");

Now you can manipulate your event further, doing whatever you want to that event, using something like:

g.event = <whateverCodeIWant>;
g.myOwnProperty2 = <whateverCodeIwant2>

Since you seem to like constructors, you can also do it like this:

function Graph (dataType, provider, evt){
   this.dataType = dataType;
   this.provider = provider;
   this.evt = evt
}

var myevt =  $.Event("whateverEvent");
myevt = <codeTomanipulatemyEventFurtherNowIfIWantTo>;
var g = new Graph("datawhatever", "providerwhatever", myevt);
$("whateverIWant").bind(myevt); 
//or whatever other binding - it will bind to that very event
$("whateverIWant").bind(g.evt);//equivalent to above line- binds to same event object
like image 143
sajawikio Avatar answered Oct 10 '22 02:10

sajawikio