Displaying articles with tag "javascript"
There are 7 articles with this tag.
21 April 2010
Outside Events is a spankin' new YUI 3 Gallery module that allows elements to subscribe to DOM events that occur outside of them. An event occurs outside the subscriber if the target it is not the subscriber itself, or any of the subscriber's ancestors. Many common outside events are pre-defined and ready to use, and defining new outside events is a cinch.
Outside Events is tiny weighing in at 475 bytes minified and gzipped. It's also hosted on the same CDN as YUI 3, so including it in your projects is simple and fast.
YUI({
// Last Gallery Build of this module
gallery: 'gallery-2010.04.21-21-51'
}).use('gallery-outside-events', function(Y) {
// Outside events are ready to go!
});
Subscribe to outside events just like any other DOM event. Here is the pre-defined clickoutside event in action.
Y.one('#dialog').on('clickoutside', function (e) {
this.addClass('hidden');
});
Let's say you've defined a sweet new swipe event with the YUI 3 Synthetic DOM Event API. Defining swipeoutside is easy.
Y.Event.defineOutside('swipe');
New outside events are named <event>outside by default. You can optionally give new outside events a custom name.
Y.Event.defineOutside('swipe', 'outerswipe');
Y.one('#foo').on('outerswipe', ... );
Outside event handlers receive the originating DOM event object as an argument.
Y.one('#foo').on('keyupoutside', function (e) {
var tag = e.target.get('tagName'),
text = 'A keyup event occured on a ' + tag + ' element ' +
'outside of #foo';
alert(text);
});
To learn more about Outside Events and view the list of pre-defined outside events, have a look at the YUI Library page and the README, which goes into detail about a few general caveats and specific known issues with IE 6, 7 and 8 you should be aware of.
28 August 2008
24 June 2007
According to this Microsoft KB article, memory leaks caused by circular references or closures in JavaScript have been eradicated from IE6 on Windows XP.
After all these years dealing with this problem, it sounds almost too good to be true. via
13 June 2007
Over the past few weeks I've noticed forums and blogs near and far having discussions on how to safely parse JSON in JavaScript. Most of these conversations hinge upon something like "because eval is simply not enough." And they are right.
So, how do you safely parse JSON in JavaScript? Luckily for us, Doug Crockford has done the work for us. Simply include his json.js in your project, and all String objects will have a safe parseJSON method. It uses a regular expression to weed out malformed and possibly malicious JavaScript.
In addition, you'll also find that the Array, Boolean, Date, Number, Object and String types have a toJSONString method that converts a JavaScript value to a JSON value.
Here's a quick and dirty example:
var json = {
'foo': 12,
'bar': 'beer',
'baz': ['fish', 'fleas', 'fools']
}.toJSONString();
console.log(json); // Prints JSON string
// Safely parse JSON string
json = json.parseJSON();
console.log(json); // Prints JSON object
17 May 2007
When I first mentioned JSONQuery, I actually posted the core functionality of a more comprehensive parser. While I tried to keep things simple by writing queries in JavaScript, the task at the time required a tiny slice of custom syntax. Because JSONQuery grew in size, and in order to keep things simple, I stripped out the custom bits before writing up the original post. In hindsight, I realize the original code may be more complex than it needs to be.
If JSONQuery accepts queries written in JavaScript, why should we waste time with a custom parser when JavaScript has a built-in parser, namely eval? That all depends on how you feel about eval. For example, Douglas Crockford famously frowns upon eval:
The
evalfunction (and its relatives,Function,setTimeout, andsetInterval) provide access to the JavaScript compiler. This is sometimes useful for parsing JSON text, but in virtually all other cases it indicates the presences of extremely bad coding. Theevalfunction is the most misused feature of JavaScript.
JSONQuery is at its core a JavaScript parser. Since any JSON text has presumably already been parsed and converted into an Object, what we're actually building is a general purpose Object query. So, assuming you're comfortable with eval in this context, JSONQuery evolves into Object.query and becomes even simpler. Here is the new Object.query in action:
Object.prototype.query = function(query) {
var result = eval('this.' + query);
return !!result ? result : null;
};
var json = {
'name': 'Bob',
'address': [{
'street': '1234 Main St.',
'city' : 'New York',
'state': 'NY',
'zip': '10101'
},{
'street': '5678 First St.',
'city' : 'San Francisco',
'state': 'CA',
'zip': '94126'
}]
};
json.query('address[1].zip'); // 94126
Of course, there are still issues present in this minimalist implementation. Are we certain query is a String? Are we certain query is safe to eval? Are there other sanitizations we should perform? What can be done about any parse errors during eval? These are basic issues that can be easily corrected before putting Object.query into the wild.
These issues aside, the evolution of JSONQuery to Object.query has several benefits. It's much easier to understand what's happening. By its nature, eval is much faster than the original parser. Finally, it's more useful as a method present on any Object. All of this assumes, of course, that there is a need to retrieve the value of a specific property of an object at any given depth dynamically, using queries generated at run-time.
13 April 2007
I stumbled on a job listing at Meebo today, calling for a JavaScript Ninja. The job description poses a few JavaScript puzzles for candidates to solve and submit along with their résumés.
Perhaps the trickiest puzzle of the lot would be #3, since its topic is only recently becoming more well known: using a double-bang (!!) in a boolean test. I found the rest of the puzzles, however, to be fairly straight forward, and not very tricky at all. I would imagine that a true JavaScript Ninja would be subjected to a more rigorous test of skill than these small puzzles.
Realistically, the puzzles are a great way to weed out those who've seen JavaScript from those who know JavaScript. In fact, they have given me some great ideas for new interview questions to add to my aging bag of tricks.
3 April 2007
Update: It turns out this problem was more easily solved. I write about it in a follow-up post, JSONQuery Redux.
Let's assume you have a JSON object with a predictable structure. Let's also assume you need a way to retrieve the value a specific field, at any given depth, dynamically. That is, you don't know ahead of time exactly which field's value you need. The query will be generated at run time.
JSONQuery allows you to access the value of a specific field of a JSON object by applying a query string written in JavaScript syntax.
Here's a simple example of JSONQuery in action:
var json = {
'name': 'Bob',
'address': [
{
'street': '1234 Main St.',
'city' : 'New York',
'state': 'NY',
'zip': '10101'
},
{
'street': '5678 First St.',
'city' : 'San Francisco',
'state': 'CA',
'zip': '94126'
}
]
};
var query = 'address[1].zip',
val = jsonQuery(json, query);
console.log(val); // 94126
I realize at first glance it may seem silly to even go down this path. But the need arose recently where I needed something just like this. It may still be silly, but it works damn well. If you have suggestions or improvements, please share.
Full JSONQuery code:
function jsonQuery(json, query) {
var params = query.split('.'),
result = json;
for (var i = 0, length = params.length; i < length; ++i) {
var parts = params[i].split('['),
index = null;
for (var j = 0, len = parts.length; j < len; ++j) {
index = parts[j].replace(/\]$/, '').replace(/'/g, '');
if (!result || !result[index])
return null;
result = result[index];
}
}
return result;
}



