Search code examples
drypnotify

How to use eval on jquery plugin variable?


I'm using pnotify, the JQuery plugin. I want to shorten this code:

$.pnotify.defaults.styling = "jqueryui";
    $.pnotify.defaults.delay = 1500;
    $.pnotify.defaults.title = 'Error'
    $.pnotify.defaults.mouse_reset = false;
    $.pnotify.defaults.history = false;

Into something like this:

var darray = { 'styling':'\'jqueryui\'', 'delay':'1500', 'title':'\'Error\'', 'mouse_reset':'false', 'history':'false' };
$.each(darray, function(option,choice){
        eval("var $.pnotify.defaults." + option + "=" + choice + ";");
        });

However, despite trying all sorts of things, I have failed. Here's some of the things I've tried:

var darray = { 'styling':'\'jqueryui\'', 'delay':'1500', 'title':'\'Error\'', 'mouse_reset':'false', 'history':'false' };
$.each(darray, function(option,choice){
            eval("var $.pnotify.defaults." + option + "=" + choice + ";");
            });

JSONstring='var $.pnotify.defaults.' + option + "=" + choice + ";";
$.parseJSON(JSONstring);

string99 = 'var $\.pnotify\.defaults\.' + option
$.parseJSON('{string99=choice}');

option='var $.pnotify.defaults.'+option;
var JSONObject= {'option':choice};
$.parseJSON(JSONObject);

Fiddle: http://jsfiddle.net/morossive/kayKn/


Solution

  • You could try this (untested, but you get the idea):

    var darray = {
        styling: 'jqueryui',
        delay: 1500,
        title: 'Error',
        mouse_reset: false,
        history: false
    };
    
    for (var mbr in darray) {
        $.pnotify.defaults[mbr] = darray[mbr];
    }
    

    Because JavaScript treats objects like hashtables, we can iterate over their "keys" (for (var mbr in darray)) and assign new values to new keys in objects. For example:

    var obj = {...};
    
    // The following are equivalent:
    obj.x = 5;
    obj['x'] = 5;
    

    However, I think there may be an even more elegant solution to your problem (don't use this if you are worried about overwriting preexisting values in $.pnotify.defaults, however):

    $.pnotify.defaults = {
        styling: 'jqueryui',
        delay: 1500,
        title: 'Error',
        mouse_reset: false,
        history: false
    };
    

    I know you asked how to use eval to solve this, but I think in general any alternative to using eval is probably better.