views:

69

answers:

2

Hi, and thanks for looking.

Currently I am implementing code from this example. In my aspx file, I have Label1 and Textbox1 defined. In my aspx.cs file, I am setting the Label1.Text property to a random string in the Page_Load method.

In the .js file I have included, I have:

var Label1, TextBox1;

Sys.Application.add_init(AppInit);

function AppInit(sender) {
    Label1 = $get('Label1');
    TextBox1 = $get('TextBox1');

    $addHandler(Label1, "click", Label1_Click);
    $addHandler(TextBox1, "blur", TextBox1_Blur);
    $addHandler(TextBox1, "keydown", TextBox1_KeyDown);
}

Now, I want to add more labels (and corresponding textboxes), but I do not want the overhead of defining separate handlers for each of the additional events, i.e. I want to avoid this:

$addHandler(Label1, "click", Label1_Click);
$addHandler(TextBox1, "blur", TextBox1_Blur);
$addHandler(TextBox1, "keydown", TextBox1_KeyDown);
$addHandler(Label2, "click", Label2_Click);
$addHandler(TextBox2, "blur", TextBox2_Blur);
$addHandler(TextBox2, "keydown", TextBox2_KeyDown);
...

How can I pass a parameter to the handler that will identify the sender accurately, and have the handler use 'this' or something. Also of note, I want to be able to identify the index of the Label (1,2,3...) because I have to edit the corresponding textbox as well. FOr instance, the current implementation of Label1_Click looks like this:

function Label1_Click() {
    TextBox1.value = Label1.innerHTML;
    Label1.style.display = 'none';
    TextBox1.style.display = '';
    TextBox1.focus();
    TextBox1.select();
}

Thanks, you guys.

A: 

Hey,

Well, $addHandlers can help speed up the process of adding handlers... also, in JS you can attach miscellaneous data to objects by doing: Label1["somenewproperty"] = value; and so you can attach certain attributes and check in the event handlers... that does take up resources though, so be careful how much you do this...

On some level, how is JS supposed to know the objects you want to listen to and what order the objects are in, to reduce the amount of code? Maybe storing an array of textboxes and labels, and referring to those objects by index, but on some level, you can't get away from certain plumbing code.

HTH.

Brian
A: 

You can try creating a delegate. For example with your labels:

function AppInit(sender) {
  $addHandler(Label1, "click", Function.createDelegate(this, LabelClick());
  $addHandler(Label2, "click", Function.createDelegate(this, LabelClick());
}

function LabelClick(sender)
{
 /..
}
Gary
is that similar to a callback? I was thinking of playing with this...
Freakishly
Yes, except delegate specifically returns the sender. Callback lets you return anything (so if your callback returns the sender itself then its same thing). In fact, if you need both, you can do createDelegateCallback.See: http://blogs.lotterypost.com/speednet/2008/5/aspnet-ajax-client-library-combining-create.htm
Gary