views:

214

answers:

2

I have been working on this script:

<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript">
$(function(){
    compentecy = $('#competency_id');
    $('#add_competency').bind('click', function(e){
        e.preventDefault();
        $.post('/script.php', {competency_id: compentecy.val(), syllabus_id: 2}, function(){
            // competency = $('#competency_id');
            competency.children('option[value=' + compentecy.val() + ']').remove();
        });
    });
});
</script>

in the $.post callback function, it seems that I can't access global variables. I tried $.competency but it didn't work. I always get a "competency is undefined" error. I had to reinitialize the variable once again inside the callback. Is there a way to NOT reinitialize the variable inside the callback?

+1  A: 

You could use .proxy() like this:

$.post('/script.php', {competency_id: compentecy.val(), syllabus_id: 2}, 
  $.proxy(function(){
    this.children('option[value=' + this.val() + ']').remove();
  }, compentecy)
);

$.proxy() lets your determine what this is inside the callback, just for cases like this :)

Nick Craver
that's good to know.
Thorpe Obazee
+1  A: 

OMG. it's one of those days I guess. spelling of the variable was incorrect :P

Thorpe Obazee
Glad you spotted it. :) BTW, you should declare the variable first with `var competency = $('#competency_id');` to restrict the scope to within your function and its nested functions, otherwise it'll be attached to the global `window`.
deceze
Shit happens, lol
Ben