3

I am writing a widget template, which will be included in a page where it is installed.

One may install several of the same kind of widget in one page, so my template may get included several times.

Now I have written some JavaScript to initialize the widget, you know, the clickings and hoverings.

My problem is that these <script>s get executed multiple times, for example, when I click something, the bounded function get executed several times.

What is the best way to solve this problem?

EDIT:
By the way, I am using the Mako template engine, and I've tried using the c variable to store a boolean flag, but it seems that the c get overridden every time.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
satoru
  • 31,822
  • 31
  • 91
  • 141
  • online include the ` – Manse Nov 29 '11 at 09:42
  • see http://stackoverflow.com/questions/3678628/javascript-run-once-without-booleans – Manse Nov 29 '11 at 09:44

1 Answers1

5

What about a similar solution to the one that's been used in C to prevent header-files to be included multiple times?

For example in the file "example.html" you could wrap your code in an if-statement like this:

<script type=text/javascript>
    if (!window._EXAMPLE_HTML_) {
        window._EXAMPLE_HTML_ = true;
        // your code goes here
    }
</script>
Torben
  • 6,317
  • 1
  • 33
  • 32
  • I don't know how to share a variable between `included templates` with my template engine :( – satoru Nov 29 '11 at 09:58
  • @Satoru.Logic a global variable belongs to the browser not the script - so its available everywhere – Manse Nov 29 '11 at 10:12
  • BTW: It's not the best style to add _EXAMPLE_HTML_ to the window object. Better create another global object somewhere and use this. – Torben Nov 29 '11 at 10:18
  • What scope does the global object live in if not `window`? – Joe Aug 12 '13 at 13:59
  • Sure, it's a property of window, so the example is ok if you only need one variable. However, it would be a bit cleaner to use something like `window._INCLUDES_.EXAMPLEONE_HTML` and `window._INCLUDES_.EXAMPLETWO_HTML` if you need more than one, since this won't pollute the global scope with more variable names than necessary... – Torben Sep 02 '13 at 22:12