Just a quick tip. While Aptana Studio doesn’t have an editor mode for Stylus (an awesome CSS dialect) yet, it seems to work quite well when configured to treat .styl files as CSS files. The syntax highlighting looks good, it can mostly auto-complete CSS properties and values (depending on how much you use Stylus radical syntax) and can even spot some errors (though it does obviously treat some of Stylus syntax as errors, but not as much as one would expect).
To tell Aptana Studio to open Stylus files with the CSS editor, go to Window -> Preferences -> General -> Editors -> File Associations -> Under File types click Add… -> Under File type enter *.styl -> Click Ok -> Under Associated editors click Add… -> Select CSS Source Editor -> Click Ok.
If you want to see real Stylus support added to Aptana Studio, bug them about that in the ticket I opened :-)
Content scripts on Chrome extensions run on a different context than the page they’re running on. They can access and manipulate the DOM, but they don’t have access to any variables of functions defined in the webpage.
It is, however, possible to inject new <script> tags into the page and execute code from there. Yet, passing data from the content script scope and getting data back isn’t very convenient – which is why I wrote a small function to make that easier.
To pass data into the webpage context, the inject function takes a function as its last arguments and passes all the arguments preceding it to that function. To get data back from the webpage context I’m taking advantage of the fact that appendChild is synchronous and blocks execution until the script is finished executing by replacing the <script> innerText with the return value.
Do note that all the data is exchanged in JSON format, so only primitive values and simple array/objects can be passed. When the code causes an exception, its stringified and thrown in the content script context (a magic isException property is used for that, so be careful not to use it for other purposes).
Here’s the function (written in CoffeeScript. For those of you still using JavaScript, the JavaScript version is available at the gist):
Just a quick post about a benchmark that quite surprised me. The array plus operator ($arr1 + $arr2) is over 6 times faster compared to array_merge. I did expect that to be faster, but not that much. This is the benchmark I used:
nadav@shesek:~$ time php -r '$x=array("x"=>1, "y"=>2); $y = array("y"=>3, "z"=>4);
> for ($i=1; $i<=500000; $i++) { $y + $x; }'
real 0m1.437s
user 0m1.392s
sys 0m0.024s
nadav@shesek:~$ time php -r '$x=array("x"=>1, "y"=>2); $y = array("y"=>3, "z"=>4);
> for ($i=1; $i<=500000; $i++) { array_merge($x, $y); }'
real 0m9.994s
user 0m7.472s
sys 0m2.400s
The results were about the same for several executions.
A couple of things should be be noted about the array plus operator:
As opposed to array_merge, it overwrites numeric keys too. If you need to merge the values of two arrays with numeric keys, use array_merge instead
If you need recursive merge, use array_merge_recursive instead.
The values from the first array overwrites the values from the second, as opposed to array_merge. So the equivalent of array_merge($a, $b) is $b + $a, not $a + $b.
I’ve been looking for something to notify me about new GitHub notifications, and didn’t find anything. As I also wanted to take a look at the desktop notifications API, I decided to write a small Chrome extension that displays GitHub’s notifications as desktop notifications.
There’s no API or feed to get those notifications from, so I ended up scraping that data from the HTML page using XmlHttpRequest. The options page lets you set the interval for checking for new notifications.
I’ve thought today on a nice and clean way of handling default function arguments in JavaScript. Because the arguments object in JavaScript defines getters and setters that also interact with the functions’s formal arguments, changing its values also changes the value of the local argument variables. For example:
function foo(bar) {
arguments[0] = "baz";
alert(bar); // bar is now "baz", not "qux"
}
foo("qux");
What that means is that we can pass the arguments object to another function, which can take care of setting default values and by that also modify our local argument variables:
window.setDefault = function (args) {
for (var i = args.length + 1; i<arguments.length; i++) {
args[i-1] = arguments[i];
}
};
// Minified:
// window.setDefault=function(a){for(var b=a.length+1;b<arguments.length;b++)a[b-1]=arguments[b]}
When displaying values in HTML templates, you would usually want to escape special HTML characters so that they’re displayed properly and to protect against XSS.
I’ve changed my local Underscore.js (and opened a pull request at Underscore.js’s github) to add support for _.escape() and a new <%== ... %> template syntax (notice the double equal signs) which escapes the value for displaying it in HTML.
If you want to add support for that, you can either apply my commit or simply use this code (make sure to load that after Underscore.js):
If you prefer and have no backward-compatibility issues with it, you can change the <%= ... %> syntax to be escaped by default, and use the double equal sign for cases you do want unescaped HTML. Use that code instead:
The nature of javascript makes it quite easy to have singleton-like behavior without actually using the singleton design pattern – simply define an object with some properties and use that. No need to do anything more than that, really – there’s no reason to create a prototyped function, create an instance and keep a reference to it when javascript gives you a much more natural and elegant solution.
For example:
var Foo = {
bar: 123,
a: function() { /* ... */ }
/* ... */
};
// Simply use Foo as a "singleton"
However, one thing that is missing from the singleton pattern is that the constructor is called only once, and only at the moment someone requests an instance, so it doesn’t run any code to initialize the object unless actually necessary.
Here’s my way of doing that in javascript:
var ObjectInitializer = function(object) {
var initialized = false;
return function() {
if (!initialized) {
object.initialize();
initialized = true;
}
return object;
};
};
To use that, simply add an initialize property on the object with the code to execute when the object is requested the first time, and pass it to ObjectInitializer, which’ll return an anonymous function that calls the initialize method the first time its accessed and returns the object, or simply returns the object otherwise.
If you’re using collections and models as attributes for other models, calling toJSON() on Backbone.Model objects isn’t very useful as it returns the models and collections as-is. I’ve opened an issue requesting to make it recursive, but it seems like its not going to be added.
If anyone still wants this functionality, you can use that modified version of Backbone.Model.prototype.toJSON that I added to the issue:
If your blog has large number of comments in the moderation queue, akismet “check for spam” option that tries to filter out spam from your moderation queue could execute for too long, die, and return either a blank page or a ‘page not found’ error.
However, Akismet does manage to check some comments every time you run it, so if you’ll keep refreshing it you’ll see the number of comments in the moderation queue drop slowly.
As I have over 50K of comments in the moderation queue and no time to keep hitting refresh, I wrote a small hacky javascript code that does that automatically by refreshing an iframe. Just paste the following code in the address bar while you’re on any page (make sure you change YOUR-WORDPRESS_URL) and let it run for some time (make sure the page you wrote that in stays open):
Many times I add UI enhancements using jQuery UI, like buttons, datepickers, tabs, etc that requires very simple JavaScript code without much logic. Having to add JavaScript code for those small enhancements quickly became annoying for me. To overcome this, I’ve been using CSS classes like “jq-datepicker”, than execute $(‘.jq-datepicker’).datepicker() in a file that’s globally used on all pages of the website – a much better solution, but not quite perfect.
Today I thought on a very simple concept that makes is extremely easy to create jQuery UI widgets from HTML markup – why not simply add an attribute with the jQuery method to execute on the element?
Technically? No. HTML5 does support custom attributes when their name is prefixed with ‘data-’. However, the HTML5 specs are not done yet and its not fully supported in all browsers.
That being said – it does currently work well on all the major browsers and you know it’ll continue working into the future when HTML5 is officially out. Also, if you’re use the HTML5 DOCTYPE (<!DOCTYPE html>), it’ll pass HTML5 validation.
What about arguments?
What if you need to pass arguments to that call? I personally think that those arguments doesn’t belong in HTML. The purpose of this isn’t to have your JavaScript logic in your HTML, but merely mark that an element should use a specific widget. If you need arguments, create a custom jQuery.fn method that wraps the call to the jQuery method with those arguments (or any other complex logic), than use that method. For example, if you want to use the datepicker widget with a different dateFormat, create jQuery.fn.mydatepicker() method:
Than you can define an ‘data-jqa’ attribute with a JSON string. It can either be a single argument, or an array of arguments. For example, to set the dateFormat using that attribute, you could this code which’ll produce the same result as above:
Do note that it uses jQuery.parseJSON(), which requires a valid JSON string, so you must use double quotes for string literals and quote the object keys, which makes the HTML somewhat ugly, especially with the html encoding for the quotes.