Search code examples
javascriptjqueryobject-literal

Creating reuseable variables within a .on() or any object literal


Sometimes I run into situations where I'm having to create the same variables, and retrieve the exact same type of information over & over again while inside of a object literal, such as an .on() Out of sheer curiosity, and the fact that there has to be a better way, here I am.

NOTE I am not talking about jQuery .data() or any sort of normal window. global variable. I am talking one that is maintained within the closure of the object literal.

Some of these variables change in real-time of course, hence why I always had them inside of each method within .on()

Case in point:

$(document).on({
    focusin: function () {
        var placeHolder = $(this).attr('data-title'),
            status      = $(this).attr('data-status');
        // etc etc
    },
    focusout: function () {
        var placeHolder = $(this).attr('data-title'),
            status      = $(this).attr('data-status');
        // etc etc
    },
    mouseenter: function () {
        // same variables
    },
    mouseleave: function () { }
}, '.selector');

Is there a way to just have the variables stored somewhere, and retrieve on each event? They need to be dynamic

$(document).on({
     // Basially:

     // var placeHolder; etc
     // each event gets these values

     focusin: function () {
         // now here I can simply use them
         if (placeHolder === 'blahblah') {} 
         // etc
     }
}, '.selector');

Solution

  • You can use event data to pass some static variables to the event, as well as to make a method-wise trick to pass the "dynamic" ones:

    $(document).on({
        focusin: function(e) {
            var attrs = e.data.getAttributes($(this)),
                var1 = e.data.var1;
    
            var placeHolder = attrs.title,
                status = attrs.status;
            // ...
        },
        focusout: function(e) {
            var attrs = e.data.getAttributes($(this)),
                var1 = e.data.var1;
    
            var placeHolder = attrs.title,
                status = attrs.status;
            // ...
        },
        // ...
    }, ".selector", {
        // static variables
        var1: "some static value",
    
        // dynamic "variables"
        getAttributes: function($this) {
            return {
                title: $this.data("title"),
                status: $this.data("status")
            };
        }
    });
    

    DEMO: http://jsfiddle.net/LHPLJ/