Shortcut to call js function

Is there a shortcut for this kind of thing:

<%if X=42%>
<script type="text/javascript>
some_funct()

<%end%>

Mk 27 wrote:

Is there a shortcut for this kind of thing:

<%if X=42%>
<script type="text/javascript>
some_funct()

<%end%>

I’m not sure, but if there isn’t, a helper method would be trivial to
write. However, you probably shouldn’t be writing that sort of code in
the first place:

  • “if X=42” should be “if x == 42”.
  • JavaScript belongs in external files, not in the view. (Just like CSS
    – although you can include it inline, it’s a very bad idea.)
  • Depending on what you’re doing, this may be too much logic for the
    view.

Best,

Marnen Laibow-Koser
http://www.marnen.org
[email protected]

Sorry, yeah, that should be ==

some_func() is in an external file, but it does need to be called from
in the view. Your assertion that “javascript does not belong there” is
patently ridiculous since many of the normal rails functions deploy
JS/AJAX, in the view. A central conceit of rails is XMLHttpRequest, and
it is deployed IN THE VIEW.

I will investigate writing a helper, thanks.

Mk 27 wrote:

Sorry, yeah, that should be ==

some_func() is in an external file, but it does need to be called from
in the view.

Why? What does it do? Can you use event handlers instead?

Your assertion that “javascript does not belong there” is
patently ridiculous

No it’s not. It is in fact generally accepted, though there may be a
little disagreement over precise details. (I’ll admit that I tend to be
towards the extreme side of the debate.)

since many of the normal rails functions deploy
JS/AJAX, in the view.

Yes, this is one reason I’m not all that keen on the implementation of
Rails’ JS helpers (although lowpro greatly helps, and it’s certainly far
easier than doing Ajax without helpers).

A central conceit of rails is XMLHttpRequest, and
it is deployed IN THE VIEW.

I wonder if we’re using “in the view” in the same sense here. Certainly
it’s true that the XmlHttpRequest is triggered in the view, but the
JavaScript code for it should be in a separate file from the
HTML/ERb/Haml/whatever. (Yes, I’ve used these principles in complex
Ajax apps.)

Generally speaking, it should never be necessary to have any more JS in
your HTML files than you can fit into a simple onclick attribute
(actually, even that’s not strictly necessary, and I prefer to avoid it
when I can through good use of onload). In particular, tags in
the body are almost certainly a sign of poor design practice (the
exception would be for external libraries like Google Analytics and
Facebook Connect).

In sum, then…please don’t tell me what I say is “patently ridiculous”
unless you’re sure of it. Rails does not always do things in the best
way possible where generating JS (and SQL) is concerned.

I will investigate writing a helper, thanks.

OK.

Best,

Marnen Laibow-Koser
http://www.marnen.org
[email protected]

Marnen Laibow-Koser wrote:

In sum, then…please don’t tell me what I say is “patently ridiculous”

It still seems to me that it is. Where there is html, there can be
javascript. I would far rather use one line

On May 29, 2009, at 4:13 PM, Marnen Laibow-Koser wrote:

write. However, you probably shouldn’t be writing that sort of code
Best,

Marnen Laibow-Koser
http://www.marnen.org
[email protected]

On May 29, 2009, at 4:26 PM, Mk 27 wrote:

I will investigate writing a helper, thanks.
It already exists:

<%= javascript_tag(“some_func()”) if x == 42 -%>

-Rob

Rob B. http://agileconsultingllc.com
[email protected]

Rob B. wrote:

I will investigate writing a helper, thanks.
It already exists:

<%= javascript_tag(“some_func()”) if x == 42 -%>

Thanks Rob! I was sure I had run across this somewhere, but I have been
rummaging thru so much new material while learning I was totally
clueless as to where. Perhaps I should take more notes…

Mk 27 wrote:

Marnen Laibow-Koser wrote:

In sum, then…please don’t tell me what I say is “patently ridiculous”

It still seems to me that it is. Where there is html, there can be
javascript.

Yes. There can also be CSS. There should be neither.

I would far rather use one line


in your HTML, then do something like

window.onload = function () {
$$(‘.menu’).each(function (div) {
createMenuDiv(e);
};
};

in the separate JS file. Much cleaner; much better separation of
presentation and behavior. Almost (M)VCish – the JS is sort of the
client-side controller.

Also, using an event handler still
entails putting some javascript in an html page somewhere.

Not necessarily. You can use the onload technique (as above) to assign
behavior without a single JS call in the HTML. All you need is the
external tag in the .

You have hit a paradox by saying that you want to use prototype, etc.
but you do not want to see any js calls in your html files.

It’s not a paradox at all. It’s perfectly feasible, and I know because
I have done it.

I do
understand it is an explicit goal of rails to minimize the amount of js
that the developer has to deal with personally, but I am already
comfortable with it.

So am I – comfortable enough to know that I don’t like Rails’ approach
that much (although I do use it here and there for simplicity’s sake).

I could tie my left hand to the chair in order to
guarantee that only my right hand will be used for typing, but why
bother?

I’m really not impressed by the analogy. Properly separated JS is a
little harder to set up initially, but is much easier to deal with
later. Come to think of it, the same could be said of frameworks such
as Rails…

Anyway, Marnen, these are cosmetic preferences. I would just hate to
see the day when some weirdo consortium comes along and says “From now
on, everyone must tie their left hand to the chair”, altho I doubt that
will be possible in this case.

Again: it is possible. It is feasible. It’s not even particularly
difficult. I have done it on a complex application, and would do it
again in similar circumstances. It is not a cosmetic preference, but
rather an architectural one. And it is not my idea alone – it comes
from the JS guidelines of Douglas Crockford ( http://www.crockford.com
), who is or was a JS architect at Yahoo! (he’s also the guy who
discovered JSON and the classical inheritance patterns in JS). If
you’re working with JS, I strongly recommend poking around his site if
you haven’t already – there’s lots of useful stuff.

*meaning there may be more unfortunate use of javascript still to come
:open_mouth:

Well, yeah…

Best,

Marnen Laibow-Koser
http://www.marnen.org
[email protected]

Mk 27 wrote:

Marnen Laibow-Koser wrote:

It still seems to me that it is. Where there is html, there can be
javascript.

Yes. There can also be CSS. There should be neither.

WHY!???!? You want to make web programming more limited that it
already is??

No, I want to separate behavior and presentation. That’s just good
architecture.
Nothing I am recommending makes Web programming any more limited. If
anything, it has the opposite effect, since it organizes the code
better.

I agree “when convienient” but

Rather what I’m talking about is simply having


in your HTML, then do something like

window.onload = function () {

  1. what if this menu is part of a view being loaded into an existing
    div, and not part of a fresh page

I think the principle still works.

  1. create_menu_div would imply (or at least, I would hope) to me
    something a little bit more significant than just assigning some style.
    I do use a function like this, and it takes an array of choices (for the
    menu options) and a callback containing a switch(); the number of the
    choice corresponds to this, so rather than having to write a slew of
    onclick statements, etc,

choices = [“do this”, “do that”, “do both”];
create_menu_div(style, choices, parnt, callback);

Not sure I understand from that description. I’ll reread when I’m less
pressed for time.

Also, using an event handler still
entails putting some javascript in an html page somewhere.

Not necessarily. You can use the onload technique (as above) to assign
behavior without a single JS call in the HTML. All you need is the
external tag in the .

The I would say is part of an html page.

Yes. That’s not what I meant. Rather, I meant that the tag
points to an external file, so there is not a single line of JS in the
HTML file.

I’m sure you already handle CSS this way, with tags pointing to
external file. Why is it so hard to grasp the concept of doing the same
for JS?

It’s not a paradox at all. It’s perfectly feasible, and I know because
I have done it.

Yeah, because you use ruby shortcuts. The JS still ends up in the page.

Wrong. The complex Ajax work I have done was in an application that did
not involve Rails, or indeed any other framework with JS helpers. I
know precisely how much literal JS wound up in the HTML generated by
that application: none. I made sure of that, and would do it exactly
the same way again in a similar case, Rails or no Rails.

All you have to do is look at the source generated for a rails app page
(any and all of them) to find more inline javascript than you can shake
a stick at.

Yes, if you use Rails’ JS helpers without the UJS or Lowpro plugins.
This is why I don’t like to do that. At the very least, use one of
those plugins to separate your JS and HTML.

Again: it is possible. It is feasible. It’s not even particularly
difficult.

Sure, and again I agree: as convenient. By “not possible” I meant that
I sincerely hope that people with your opinion do not come up with a
means of forcing everyone else to comply, and I do believe that “will
not be possible”, in fact. Thankfully.

Yeah, I don’t know that I’d want that either. Choice is a good thing,
but with choice comes responsibility – just because you can write JS
inline doesn’t mean you should.

OTOH, I really wouldn’t be at all unhappy if inline JS just dropped off
the face of the earth. It’s not an appropriate way to write
maintainable code, and it causes problems on the client side as well.

-MK

ps. with your penchant for waving credentials and experience, the
biggest question in my mind would be why the simple answer Rob gave was
evidently out of your range…

Why? Simple: because I haven’t done a lot with Rails’ JS helpers –
just enough to know that they generate more inline JS than I’m
comfortable with.

Best,

Marnen Laibow-Koser
http://www.marnen.org
[email protected]

Marnen Laibow-Koser wrote:

It still seems to me that it is. Where there is html, there can be
javascript.

Yes. There can also be CSS. There should be neither.

WHY!???!? You want to make web programming more limited that it
already is??
I agree “when convienient” but

Rather what I’m talking about is simply having


in your HTML, then do something like

window.onload = function () {

  1. what if this menu is part of a view being loaded into an existing
    div, and not part of a fresh page

  2. create_menu_div would imply (or at least, I would hope) to me
    something a little bit more significant than just assigning some style.
    I do use a function like this, and it takes an array of choices (for the
    menu options) and a callback containing a switch(); the number of the
    choice corresponds to this, so rather than having to write a slew of
    onclick statements, etc,

choices = [“do this”, “do that”, “do both”];
create_menu_div(style, choices, parnt, callback);

Also, using an event handler still
entails putting some javascript in an html page somewhere.

Not necessarily. You can use the onload technique (as above) to assign
behavior without a single JS call in the HTML. All you need is the
external tag in the .

The I would say is part of an html page.

It’s not a paradox at all. It’s perfectly feasible, and I know because
I have done it.

Yeah, because you use ruby shortcuts. The JS still ends up in the page.
All you have to do is look at the source generated for a rails app page
(any and all of them) to find more inline javascript than you can shake
a stick at.

Again: it is possible. It is feasible. It’s not even particularly
difficult.

Sure, and again I agree: as convenient. By “not possible” I meant that
I sincerely hope that people with your opinion do not come up with a
means of forcing everyone else to comply, and I do believe that “will
not be possible”, in fact. Thankfully.

-MK

ps. with your penchant for waving credentials and experience, the
biggest question in my mind would be why the simple answer Rob gave was
evidently out of your range…

To me, the greatest gain unobtrusive Javascript provides is
maintainability. You split the client-side logic (that is all
Javascript is) from the view for the same reason you split the
controller processing and buisness logic from the view with an MVC
framework. In addition to all Marnen said: your views become much
easier to test; You spend less time adapting the HTML your designer
gives you (or that you mock up yourself); It’s much easier to focus
on providing an intuitive interface for those with or without
Javascript enabled.

Just a couple specific points:

  1. what if this menu is part of a view being loaded into an existing
    div, and not part of a fresh page

$(element).live(“event”, function…)

I’m sure non-JQuery’ers have something similar

Yeah, because you use ruby shortcuts. The JS still ends up in the page.
All you have to do is look at the source generated for a rails app page
(any and all of them) to find more inline javascript than you can shake
a stick at.

Don’t use the RJS helpers, no inline JS. And if you think not using
the RJS helpers is limiting, I doubt you’ve really explored the powers
JS frameworks.

It still seems to me that it is. Where there is html, there can be
javascript.

Yes. There can also be CSS. There should be neither.

WHY!???!?

Semantic markup that knows little about how it’ll be displayed is far
easier to maintain, and offers more presentational flexibility via
your stylesheets.

On May 29, 7:52 pm, Marnen Laibow-Koser <rails-mailing-l…@andreas-

Marnen Laibow-Koser wrote:

The I would say is part of an html page.

Yes. That’s not what I meant. Rather, I meant that the tag
points to an external file, so there is not a single line of JS in the
HTML file.

Alright, I’ll think about it. I have probably written <1000 lines of
.js in my life*, no doubt there are angles and possibilities I am not
aware of.

Here is an example callback for the menU_div_create function I
mentioned, if this will clarify with the crude “switch” mechanism:

function mainmenu (num) { switch (num) {
case 0: if (!DBname) { alert(“You must create a new database
first!”); break; }
var tmp=prompt(“Record name:”);
new ListRecord(tmp); break;
case 1: if (current==-1) { alert(“No record selected!”); break;
}
var tmp=prompt(“Field name:”);
new formDBentry(tmp,undefined); break;
case 2: submit_form(); break;
case 3: window.open(“mkdb_load.pl”,"_self"); break;
case 4: tmp=prompt(“Database name:”);
if (tmp == “”) break;
DBname=tmp;
clear_start();
default: break; }
}

the array corresponding to this (5 options that are the text for the
menu):
var mmenu=[“Add Record”, “Add Field”, “Save”, “Load”, “New”];

and here is the “real” make_menu function, it does not actually involve
a div; but usually the “parnt” is (and “callback” is the function
above):

/* make_menu is not real OO */
function make_menu (type, css, choices, callback, parnt) {
var i=0;
var tmp, strng;
do { tmp=document.createElement(type);
tmp.setAttribute(“class”,css);
strng=callback+"("+i+")";
tmp.setAttribute(“onclick”,strng);
tmp.textContent=choices[i];
parnt.appendChild(tmp);
i++; } while (choices[i]);
}

I haven’t used this in rails, but I am using js functions that to my
mind are similar in the sense that I do not see a way out of inlining
them. Hopefully, in time I will learn.

*but I am still snobbish coming from “the real languages” :wink:

On May 30, 5:31 pm, Jonathan R. <rails-mailing-l…@andreas-
s.net> wrote:

Curious if someone in the Rails community has figured out a good way to
accomplish what Rails helpers do (controller logic in the controller
instead of view, DRY for js idioms, etc) but in an “unobtrusive” idiom
where no JS (apart from to load external js) is embedded in
the HTML. It’s not entirely obvious how to accomplish this, but I think
it’s probably possible, probably using some design where the actual
external js files are dynamically created themselves, not just static on
disk.

That’s what the UJS plugin does/did (and the rails helpers in rails 3
will apparently be more unobtrusive)

Fred

Mk 27 wrote:

You have hit a paradox by saying that you want to use prototype, etc.
but you do not want to see any js calls in your html files. I do
understand it is an explicit goal of rails to minimize the

Look up “Unobtrusive javascript”. Eg

You can keep almost all javascript out of HTML except for simply loading
external script files which then attach the appropriate javascript
behaviors where necessary.

I have become quite enamored of this approach, I think it both
facillitates more maintainable code with proper seperation of concerns,
as well as facillitates better ‘accessibility’ (not just for non-js
user-agents, but the possibility of swapping in different js
functionality for different contexts and/or user-agents).

And as I become more enamored of this approach, I’m more and more
unhappy with Rails js helpers, which definitely don’t follow it.

Curious if someone in the Rails community has figured out a good way to
accomplish what Rails helpers do (controller logic in the controller
instead of view, DRY for js idioms, etc) but in an “unobtrusive” idiom
where no JS (apart from to load external js) is embedded in
the HTML. It’s not entirely obvious how to accomplish this, but I think
it’s probably possible, probably using some design where the actual
external js files are dynamically created themselves, not just static on
disk.

Mk 27 wrote:

However, “getting the inline js” out will inevitably increase the actual
codebase of the project as whole, because you will have to add more
lines to your external scripts than you would have used in the page
source by inlining in at least some (if not quite a few) cases.

All I can say is that in the (non-Rails) project where I’m consistently
using unobtrusive JS, this has not been my experience. It hasn’t led to
any more lines of code. This does in part depend on your HTML DOM being
fairly well structured with good classes and id’s. In my experience,
once you learn how to do it right, it’s no more lines of code to
maintain, and forces you to have better-structured HTML to boot, which
is an added advantage. But there is a bit of a learning curve, sure.

Now, if you had to give up all the Rails helper methods (that are
essentially dynamic js-code-generators), then THAT would lead to more
code. I wouldn’t want to do that.

So I’m going to check out the UJS Rails plugin that Fred helpfully
alerts us to.

But to each her own.

I was gonna try to look at your example to show you a short concise
unobtrusive JS version that would do the same thing, but I don’t
understand the case quite well enough and don’t feel like spending the
time trying to just to make a point. But my experience leads me to be
confident it would be possible.

From what I’ve read this issue should really hinge on the scale of a
project; if you have a whole team of developers whose membership is
subject to change, things like compartmentalization and generic
maintainability have to be top priorities.

However, “getting the inline js” out will inevitably increase the actual
codebase of the project as whole, because you will have to add more
lines to your external scripts than you would have used in the page
source by inlining in at least some (if not quite a few) cases. And
please, do not hand me some basic case involving onload(), and claim “oh
no, it could never be more coding, look…”. Certainly, it could never,
ever, logically be less coding.

Going back to the example to which I have been referring, you would have
to throw that whole function out and use a combination of the simple css
classing mentioned by marlen with "cut paste and modify"ing the html
that would have been the majority of the output of the function. This
added effort will no doubt be justified and enabled by a large scale,
team oriented project.

However, if you are the sole author and maintainer, the extent to which
you do this (spend extra time coding to compartmentalize all the
javascript) should really be tempered by the feasibility of doing so.
I’m down with Occam’s Razor here in that introducing a complication is a
bad idea if the justification is purely about “universal” policies of
style that have little significance for the case at hand. You are not
talking about any improvement in functionality or performance, after
all.

I would hate to consider a case where an author decided not to do
something because it required inline js. That would be ass backward
blind conformism.

-MK

Mk 27 wrote:
[…]

However, “getting the inline js” out will inevitably increase the actual
codebase of the project as whole, because you will have to add more
lines to your external scripts than you would have used in the page
source by inlining in at least some (if not quite a few) cases. And
please, do not hand me some basic case involving onload(), and claim “oh
no, it could never be more coding, look…”. Certainly, it could never,
ever, logically be less coding.

You are absolutely wrong. Since inline JS, by its very nature, is much
harder to refactor, in many, many types of cases, inline JS will lead to
significantly more code than unobtrusive external JS.

Anyway, I’m not sure conciseness is as high a priority as ease of
maintenance (although they do sometimes coincide), so your point is of
dubious relevance.

Going back to the example to which I have been referring, you would have
to throw that whole function out and use a combination of the simple css
classing mentioned by marlen with "cut paste and modify"ing the html
that would have been the majority of the output of the function.

No. Just iterate over the affected DOM elements and apply an
appropriate abstraction.

You said you were snobbish about JS as compared to “real languages”.
Well, guess what – JS is a “real” language, and quite a powerful one
too, but you can’t benefit from that fact unless you treat it as a
“real” language. That means writing complete routines in one place, not
scattered bits of inline code. […]

However, if you are the sole author and maintainer, the extent to which
you do this (spend extra time coding to compartmentalize all the
javascript) should really be tempered by the feasibility of doing so.

It is always feasible. It is (virtually) always worth doing. Stop
complaining about it and try writing a sample page or two (with or
without Rails) while keeping JS out of the HTML. I guarantee that both
your JS and your HTML will be the better for it.

I’m down with Occam’s Razor here in that introducing a complication is a
bad idea if the justification is purely about “universal” policies of
style that have little significance for the case at hand.

They have significance for every nontrivial case.

You are not
talking about any improvement in functionality or performance, after
all.

Wrong again.

I would hate to consider a case where an author decided not to do
something because it required inline js.

Read my lips: NOTHING REQUIRES INLINE JS! Anything doable with inline
JS can also be done without it.

That would be ass backward
blind conformism.

Perhaps it would be, but it’s a straw man, since it will never happen.

-MK

Best,

Marnen Laibow-Koser
http://www.marnen.org
[email protected]

Marnen Laibow-Koser wrote:

Mk 27 wrote:

And
please, do not hand me some basic case involving onload(), and claim “oh
no, it could never be more coding, look…”. Certainly, it could never,
ever, logically be less coding.

You are absolutely wrong. Since inline JS, by its very nature, is much
harder to refactor, in many, many types of cases, inline JS will lead to
significantly more code than unobtrusive external JS.

I think we are talking about slightly different things. I am not
talking about defining functions inline. I’m talking about calling
them:

represents some kind of performance issue (considering call_my_function
is already cached), I will tell you are wrong again, because you are.

I would hate to consider a case where an author decided not to do
something because it required inline js.

Read my lips: NOTHING REQUIRES INLINE JS! Anything doable with inline
JS can also be done without it.

Possibly, although you don’t make much of a case to support that. But
just because something can be done one way or another doesn’t mean it
has to be, unless you have a good reason for it, and since you still
have not come up with one, I am satisfied that it doesn’t exist.

MK

Mk 27 wrote:
[…]

I think we are talking about slightly different things. I am not
talking about defining functions inline. I’m talking about calling
them:

represents some kind of performance issue (considering call_my_function
is already cached), I will tell you are wrong again, because you are.

What do you mean that call_my_function is already cached? I would like
to make sure I fully understand your assertion before I answer it.

I would hate to consider a case where an author decided not to do
something because it required inline js.

Read my lips: NOTHING REQUIRES INLINE JS! Anything doable with inline
JS can also be done without it.

Possibly, although you don’t make much of a case to support that.

I hope and believe that I have made quite a case. So has pharrington in
this thread (far better than me). If there’s something that doesn’t
convince you, please ask about it. If there’s something you don’t
believe is doable with inline JS, let’s see it!

But
just because something can be done one way or another doesn’t mean it
has to be, unless you have a good reason for it, and since you still
have not come up with one, I am satisfied that it doesn’t exist.

I believe that I have come up with good reasons – ease of maintenance,
separation of presentation (view) and behavior (controller), caching,
all that other good stuff. But since when did I become the only source?
Read Doug Crockford’s writings. Read pharrington’s posts here. Read
the Wikipedia article on unobtrusive JS. Read almost anything on decent
JS architecture. Notice that others in this thread consistently come
out in favor of unobtrusive JS.

Above all, please realize that nothing I have said was meant as a
personal attack. You seem to be reacting as if I insulted your little
sister (I don’t know if that’s the impression you meant to convey), when
in fact I’m just trying to give you some useful guidelines for
programming practice. I hope you will take my comments in the spirit in
which they have been intended, as I also have attempted to do.

MK

Best,

Marnen Laibow-Koser
http://www.marnen.org
[email protected]

Marnen Laibow-Koser wrote:

Above all, please realize that nothing I have said was meant as a
personal attack. You seem to be reacting as if I insulted your little
sister (I don’t know if that’s the impression you meant to convey), when
in fact I’m just trying to give you some useful guidelines for
programming practice. I hope you will take my comments in the spirit in
which they have been intended, as I also have attempted to do.

Grumble. Alright, I surrender. You win, Marnen :wink: …I think I’ve
made my point and I’ll leave it at that.

MK