简体   繁体   中英

Pass variable from one JavaScript callback anonymous function to another

As shown below, I am passing a variable from the inputclass callback to the validate callback.

Could it be done so without using a global variable so it will be local to the instance when applying the jQuery plugin to the given element?

$('#name').editable({
    inputclass: function() {
        globalVariable=this;
    },
    validate: function (value) {
        console.log(globalVariable);
        return 'pause';
    }
});

Fiddle

Since this in inputclass() and validate() are referring to different elements, it's a bit troublesome to share data. My idea is also using data(), but to pass data from inputclass() to validate(), you will need to travel up the dom from input that inputclass() refer to, up to .ui-tooltip, look for the element that validate() is referring to through id

$('#name').editable({
    inputclass: function(e, f) {
        $("a[aria-describedby=" + $(this).closest(".ui-tooltip").prop("id") + "]").data("shared", "somedata");
    },
    validate: function (value) {
        console.log("validate", $(this).data("shared"));
        return 'pause';
    }
});

Updated jsfiddle to demonstrate:

jsfiddle

I would recommend using data attributes here to pass data.

$('#name').editable({
    inputclass: function() {
        var value = 'some value';
        $(this).data('input-value', value);
    },
    validate: function (value) {
        var inputValue = $(this).data('input-value');
        console.log(inputValue);
        return 'pause';
    }
});

This method will work only if you know the inputClass function gets called before validate

PS: If you just want to pass this , there is absolutely no need for that, since it will be bind automatically in both functions.

You need to define that variable outside the scope of functions: Try this:

  var globalVariable;
    $('#name').editable({
        inputclass: function() {
            globalVariable='your value';
        },
        validate: function (value) {
            console.log(globalVariable);
            return 'pause';
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM