0

Where can I accommodate ready function in the name space?

var yourNamespace = yourNamespace || {
    foo: function()
    {
    },
    bar: function()
    {
    }
};
...
yourNamespace.foo();

ready function:

$(function(){
...
});
6
  • Your question is unclear. Why exactly do you need the ready function? Commented Sep 23, 2013 at 22:49
  • Just next to that foo() call? What do you mean by "in the namespace"? Commented Sep 23, 2013 at 22:49
  • @FritsvanCampen , I want when document is ready, inside the namespace some codes run Commented Sep 23, 2013 at 22:56
  • @Bergi i want to run this, but once namespace is defined and document gets ready: $(function(){ $('button').click(foo); }); Commented Sep 23, 2013 at 22:59
  • I'm going to migrate to namespace. Commented Sep 23, 2013 at 23:04

1 Answer 1

2

Here's how I do it:

   var MyNamespace = (function(publicAPI) {

        var foo = 'I am a  private field';

        publicAPI.alertFoo = function() {
            alert(foo);
        };

        // DOM ready
        $(function() {        
            $('.test-link').click(function() {
                publicAPI.alertFoo();
            });
        });

        return publicAPI;

    })(MyNamespace || {});

To call the alertFoo method you would use MyNamespace.alertFoo(); This is a variation of the module pattern. The DOM ready section is used for binding to events.

Sign up to request clarification or add additional context in comments.

1 Comment

MyNamespace should be the same as myModule

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.