Using prototype to define classes accessible by both the server-side (ASP) & client-side

iporter
Thu, 10 Jan 2008 23:40:35 -0000

Although some javascript objects are client-specific (i.e. document)
and others server-specific (i.e. Response), much of prototype.js can
be used on the server-side.

In building a recent application, I found myself building converting
database data into HTML objects on the server-side, to ensure it
readable by the search engines, but having to largely duplicate that
code for the client-side to redraw the HTML when the user updated
things.  I guess I could have used AJAX to get the server-side code to
return the HTML.

But I still need to have a client-side object, because I need to
unobtrusivly add client-side behaviours to the HTML.  Thus, what I''d
like to be able to do, is define a class in a .js file, and then
inlcude that .js file with both the server-side and client-side code.

If you put the code, function test() {return 1;} in a .js file,
include this file in an ASP page using a
tag,
and after this put <% Response.Write(test()) %>, you get
''1'' on the
page.  However, if you add the code, var x = 2 to the .js file, and
put <% Response.Write(String(x)) %> in your ASP page, you get
''undefined''.

Interestingly, if you then remove the code x = 2 from the .js file,
but leave the call in the ASP page, you get a runtime error 800a1391
with a message saying, ''x is undefined''.  Didn''t our
test before show
it was already undefined?

The point being, that if functions work, but variables don''t, then I
can''t use prototype''s nice, var myClass = Class.create({});
syntax.

What gives?  Can I get around this somehow?  Or perhaps this is
ridiculous and you have a better approach to the problem?

Looking forward to your thoughts,
Iain