Posted by Phil in JavaScript
on Oct 24th, 2011 | 1 comment
A couple of weeks ago I posted about C# like Properties in JavaScript. I wanted to explore how properties could possibly be added into JavaScript, and hopefully offer some insight into how some frameworks might work.
Another feature that JavaScript doesn’t explicitly support is events. Though using some of the same techniques I used for events also work very well for building events.
Most implementations of events in JavaScript use optional arguments in order to provide two overrides to an “event” function, one for adding a listener and the other for raising the event, like this:
//...
Posted by Phil in JavaScript
on Sep 14th, 2011 | Comments Off on Properties in JavaScript
JavaScript doesn’t inherently support properties in the same way that .net languages do, which is a shame since the syntax really helps simplify access internalized data in a structured way.
There’s a common solution to this in JavaScript, that exploits the fact that JavaScript function arguments are optional. A property function will have a single argument. If the argument is undefined then the current call is a ‘get’, otherwise it’s a ‘set’. jQuery has many good examples of this, for example the val() method:
var value = $('input').val(); //...