1

update: i remembered that i can store them as jQuery(document).data(key,value); for later use, but is this a good idea ? Would that be an expensive option performance-wise ?

I am trying to create var's automatically from a json array key,value pairs for later use.

So i basically created two sets of settings, 1- Default Settings (defSets) 2- User Settings (usrSets). The idea is to use user setting if it exists, otherwise fallback to default setting. I do not want to write in all vars one by one, so is there a way to create global vars from these arrays for later use in various places ?

sth along the lines like: var [key_name] = [key_value_read_from_User_Setting_or_Default_Set];

Here is my actual code below; the problem is, it seems to create the vars within the each loop, but i cant access them globally i think.

jQuery(document).ready(function(e) {
// read default settings array from cookie if exist, otherwise create initial default settings and save
  if (jQuery.cookie("defSets") != null) {
    var defSets = jQuery.parseJSON(jQuery.cookie("defSets"))
  } else {
    var defSets = { 'ord': 'true', 'itemc': 4, 'ratio': 'sq', 'sortby': 'def'};
    jQuery.cookie("defSets", JSON.stringify(defSets)); 
  };
  // read user settings array from cookie if exist, otherwise create initial empty user settings and save
  if (jQuery.cookie("usrSets") != null) {
    var usrSets = jQuery.parseJSON(jQuery.cookie("usrSets"))
  } else { 
    var usrSets = {};
    jQuery.cookie("usrSets", JSON.stringify(usrSets));
  }

  jQuery.each(defSets, function(key, value){
    // check every default setting
    if (usrSets[key] != undefined) {
  // if a user setting exists for respective default setting use that
      var key = usrSets[key];
      // uval = usrSets[key];
      // dval = defSets[key];
      // console.log("User have a setting for -" + key + "- So the value (" + uval + ") will be used instead of default: " + dval);
} else {
      var key = defSets[key];
      // console.log ("No user setting for -" + key + "- will use default val of :" + dval);
};
});

after these, ideally, i'd be able to use those var's anywhere below these lines, assuming var ratio has been already created from above; i could jQuery(".selector").height(jQuery(this).width * ratio);

4

1 回答 1

0

如果您需要全局存储一些信息,我会使用namespaces。我认为这更好,但毕竟这是一个偏好问题,我猜

于 2013-04-01T10:27:25.770 回答