views:

27

answers:

1

I don't do very much jquery / javascript but wanted to ask for some advice on the following piece. I have tried to cut out as much as possible. Most of this was semi-inherited code with catching a bunch of events just hardcoded in. I'd like to generalized them more by putting the object name in the html and accessing via jquery on processing (by_date, by_popularity). I retriev as string and access the object via window[current_obj]. Is this a good way to do this or am I missing something? Are there preferable ways to introduce specificity. thanks for any advice.

<script>
var by_date={};
by_date.current_page=1;
by_date.per_page=4;

var by_popularity={};
by_popularity.current_page=1;
by_popularity.per_page=4;

$(function(){
    $('.previous.active').live('click',function(){
        window[current_obj].current_page--;
        process(window[current_obj]);
    });
});

function process(game_obj){
   //will process and output new items here
}
</script>

<div class="otherContainer">
  <a class='previous active'>Prev</a><div style="display:none;">by_date</div> | <a class='next'>Next</a><div style="display:none;">by_date</div>
</div>


<div class="topPrevNextContainer">
  <a class='previous active'>Prev</a><div style="display:none;">by_popularity</div> | <a class='next'>Next</a><div style="display:none;">by_popularity</div>
</div>
A: 

Some would consider your code to be littering the global namespace. A common technique for achieving limited-scope in JavaScript is to define and immediately call an anonymous function.

(function() {
    // this function is anonymous and is immediately called
    // variables declared inside this function are not members
    // of the global namespace.

    var options = {};

    options.by_date={};
    options.by_date.current_page=1;
    options.by_date.per_page=4;

    options.by_popularity={};
    options.by_popularity.current_page=1;
    options.by_popularity.per_page=4;

    $(function(){
        $('.previous.active').live('click',function(){
            options[current_obj].current_page--;
            process(options[current_obj]);
        });
    });

    function process(game_obj){
       //will process and output new items here
    }
})();
Ken Browning
cool. that makes sense. so i guess not a complete hack to be doing the grabbing the value from the html text. thx
timpone