0

After discovering about Javascript namespaces, I tried to implement them but I run into a problem while trying to attach a namespace method to an element's onclick.

I used this method to wrap up my functions/methods/classes (a simplified concept, not my actual code):

;(function(window, undefined) {

    //my namespace
    var NS = {};

    NS.test = {
        f : function(param) {
            alert(param);
        }
    }

    NS.test.('test 2');

})(window);

Inside, everything works fine and "test 2" is prompted.

However, when I try to attach that function to a click event, by doing something like this:

<a href-"#" onclick="NS.test.f('test');">Click me!</a>

it doesn't work, just like it doesn't work when I call that function after the })(window); part.

I tried it calling it window.NS.test.f('test'); but with no effect.

How can I make an onclick event call my function?

I could attach an event listener inside my wrapper, like I do for other html elements with no difficulty, but it would be problematic in this case since I'm generating the links with javascript and I find it easier and simpler to just add onclick="doSomething" for all my links, instead of creating them, then cache them and add event listeners.

Call me lazy, but in this particular case I prefer to do

someDiv.innerHTML = my_Generated_Html_Code_With_OnClick;

instead of

//demo code, ignore the flaws and the fact it won't work on IE
someDiv.innerHTML = my_generated_Html_code;
myLink = document.getElementById(id);
myLink.addEventListener('mousedown', NS.test.f('test'));

I do not use any framework nor do I wish to, since I'm trying to get a better understanding of the so-called vanilla javascript first.

I set up a jsfiddle here.

P.S. I must admit I didn't understand namespaces completely so if I'm doing something wrong here or applying the concept in a way I am not supposed to, I would appreciate any tips or corrections

1 Answer 1

4

That's because NS is declared inside and hence only exists inside the function:

function(window, undefined) {
    var NS = {};

    // NS exists here ...
}

// ... but not here

If you want to make it available to the rest of the page, then you can do:

function(window, undefined) {

    var NS = window.NS = {};

    // NS and window.NS exist here ...
}

// ... and window.NS exists here.
Sign up to request clarification or add additional context in comments.

1 Comment

yes, I assumed that much. But is there any way to use it outside or do I need to rethink my code?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.