I have adopted a project that has several object literals defined – mostly for just structuring the code. Btw, not a full-time front-end developer. The problem is that some of them are defined with the jQuery onready event and some are outside. This seems really problematic to say the least. Would this be considered bad design? I’m assuming so. I have included a snippet of code that shows some of the problems, specifically the the from_inside function within obj2:
<script>
$(document).ready(function(){
alert('here i am' + obj2.handlers2.background2); // can access the obj2 value as expected
alert('make this up: ' + obj2.handlers2.tell_me2());
var obj={};
obj.handlers={
background: 'blue',
foreground: 'green'
}
});
var obj2={};
obj2.handlers2={
background2: 'here i am jt',
foreground2: 'there you are',
tell_me2: function(){
return "these are things";
}
,
from_inside: function(){
alert('color from inside jQuery: ' + obj.handlers.background); // problem here! could I get a reference to obj here?
}
};
obj2.handlers2.from_inside();
</script>
Given how we currently have it, what would be a preferable workaround? It would seem like I could pass a reference of the jQuery object to obj2 in the above but perhaps it might just be simpler to pull all the objects outside of the jQuery on ready even if at all possible.
thx in advance for any advice
edit #1
$(document).ready(function(){
$(document).on('click','#pairing-comment-submit', function(){
arc.event_handler.submit_pairing_comment.call(this);
});
... about 50 more of these
});
arc={};
arc.event_handler={
submit_pairing_comment: function(){
var id=$(this).data('the-id');
....
},
....
}
You could move the variable assignment outside of the ready function. Here’s a quick refactor:
Working example: http://jsfiddle.net/JxS7v/
The problem you were facing was due to variable scope. Variables are scoped to the function in which they reside, generally speaking. Take a look at this article: http://javascriptplayground.com/blog/2012/04/javascript-variable-scope-this