Archive for May, 2006

Prototype: bindAsEventListener()

I’ve been working on some javascript code for a client site and found a good use for binding event listeners through javascript rather than inline. There are several pages I need to add javascript code to expand each textarea on focus and collapse it on blur. So I wrote this simple function using Prototype:

1
2
3
var expandTextArea = function(event){
    Event.element(event).rows = 10;
}.bindAsEventListener(this);

The part I was unfamiliar with was .bindAsEventListener(this). It comes from the Prototype framework and is defined:

1
2
3
4
5
6
Function.prototype.bindAsEventListener = function(object) {
  var __method = this;
  return function(event) {
    return __method.call(object, event || window.event);
  }
}

While studying this, I found Simon Willison’s A Reintroduction to Javascript. I highly recommend it. At the bottom of his discussion of custom objects, he describes how to use apply() and call(). I’m not sure if my understanding is correct, but it reads to me as:

  • this is passed as the Window object to bindAsEventListener(this)
  • bindAsEventListener() returns a function that when called back by the event
  • attaches expandTextArea(event) (in this case) to object (Window) and then calls the method.

The callbacks and closures are really interesting, if a bit difficult to understand, in Javascript. I welcome comments!

Markaby Rules

I’ve been playing with Markaby the past few nights. I love it! I’m in the camp that would rather write everything in Ruby rather than mix with html and ERb. I find reading this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
error_messages_for 'laptop'

p do 
  label "Name", :for => "laptop_name"
  text_field 'laptop', 'name'
end

div do
  label "Condition", :for => "laptop_condition"
end
div do 
  collection_select("laptop", "condition_id", @conditions, "id", "description")
end

much easier and enjoyable than this code:

1
2
3
4
5
6
7
8
9
10
<%= error_messages_for 'laptop' %>

<p><label for="laptop_name">Name</label><br/>
<%= text_field 'laptop', 'name'  %></p>

<div><label for="laptop_condition">Condition</label>
<div>
<%=  collection_select("laptop", "condition_id", @conditions, "id", "description") %>
</div>
</div>

The ERb code is much noisier and therefore harder to read. The Markaby code is cleaner and more elegant.


Pages

Categories

Copyright ©2008-2013 James E Orchard-Hays, All Rights Reserved