Question

I'm definitely missing some basics here.

I'm using this plugin wich performs ajax actions, and then fires a js function as callback. I would like to use the callback in a custom js script of my theme.

Callback function is already defined (but empty) at the beginning of the main plugin js, and then fired as callback of an $.ajax post that puts values in its variables.

This is a simplified version of the plugin js

jQuery(document).ready(function(){
    new Favorites;
});

// Callback Function for use in themes
function favorites_after_button_submit(favorites, post_id, site_id, status){}

var Favorites = function()
{


    var plugin = this;
    var $ = jQuery;

    // Initialization
    plugin.init = function(){
        plugin.bindEvents();
        plugin.generateNonce();
    }

    $.ajax({
            url: plugin.ajaxurl,
            type: 'post',
            datatype: 'json',
            data: {
                action : plugin.formactions.favorite,
                nonce : plugin.nonce,
                postid : post_id,
                siteid : site_id,
                status : status
            },
            success: function(data){
                plugin.doStuff();
                favorites_after_button_submit(data.favorites, post_id, site_id, status);
            }
        });

    return plugin.init();   
}

As you can see, function favorites_after_button_submit(){} is defined but does nothing.

At first glance, I would remove that function from there and use it in my theme. But I'm sure this is not the way to do this.

SO, how could I intercept that function that is fired as callback, make available its data from another js function and use it to perform some actions?

Était-ce utile?

La solution

Ok, I found out here how to procede.

It was so simple I could not believe:

1) include in theme a custom script with a dependency on the favorite plugin. example:

wp_enqueue_script('script', get_stylesheet_directory_uri() . '/js/myscript.js', 'simple-favorite', '1.0.0', true);

2) in myscript.js just define again the function, and make it do something:

function favorites_after_button_submit(favorites, post_id, site_id, status){
    console.log('done');
}

SO, it looks like a js function can be redefined?

Autres conseils

This is more of JS question than WP, but in general the code you showed sucks. There are all kinds of ways to do callbacks in JS, the most obvious one is to pass it as a parameter in the initialization of the relevant JS code. This code is just not extendable and if it is a requirement you have you should just fork the JS and enqueue your own, but obviously this strategy is bad for maintainability.

Best option is probably to look for better plugin, or write your own (you have a code you can get inspiration from and trim the fat you do not need)

Licencié sous: CC-BY-SA avec attribution
Non affilié à wordpress.stackexchange
scroll top