1

I'm using a modular pattern for writing my JS code. I have an object with references to all my dom elements. I have put the selector for a div that I'm adding at a later point in my code execution. When I add that div, and use jQuery.css using the reference I stored in my references object, it doesn't work.

NameSpace = {
    objects: {
        someButton: $('.someButton'),
        someDiv: $('.someDiv'),
        myDiv: $('.myDiv'), //This will be added later
        //Other references
        .
        .
    },

    bindHandlers: {
        NameSpace.objects.someButton.on('click', someEventHandler);
        //Other bindings
        .
        .
    },

    eventHandlers: {
        someEventHandler: function(e){
            var div = jQuery('<div class="myDiv"></div>');
            NameSpace.objects.someDiv.append(div);

            //Doesn't work! If I use jQuery('.myDiv'), then it works,
            //but kills my modular style
            NameSpace.objects.myDiv.css({ //some styles });
        },
        //Other event handlers
    }
}
//Other code

This approach works fine for objects that exist in the page, but isn't working for a div that I add like above.

Any help?

3
  • jsfiddle.net/myrjY there are some differences between 1.9 and 2.0 check out on link Commented Jan 17, 2013 at 9:50
  • What kind of differences? I couldn't figure out a thing from your fiddle... Commented Jan 17, 2013 at 10:56
  • try switching between versions 1.9 and 2.0 Commented Jan 18, 2013 at 9:12

1 Answer 1

3

Javascript is procedural, this line myDiv: $('.myDiv') is computed only once and not everytime you call it.

It means that your selector $('.myDiv') is filled at the start of your page.

To resolve this you'd have to make your variable a function

objects: {
        someButton: $('.someButton'),
        someDiv: $('.someDiv'),
        myDiv: function(){ return $('.myDiv'); }, //This will be added later
        //Other references
        .
        .
    },

It should recalculate the selector everytime you call it.

Let me know if the trick works.

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

4 Comments

Tried it man... but it throws an error, and when console logged the objects.myDiv, it show me as a 'function'. Meaning it is getting the function assigned, but not the return value!
@RutwickGangurde Do objects.myDiv() instead.
Thanks Florian, your solution worked! Can I do this for any element that is added dynamically?
You should do this for every selector (those in your objects) of elements that are added dynamically. Doing it for all of them is not a too bad idea either as it'll be less confusing and not much more resource consuming.

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.