How to properly define a JS file for a plugins ACP page


  • Plugin & Theme Dev

    If I want to get some data other than the plugins settings on a plugin's ACP page (e.g., get members of a group and display the list of members). What's the proper way of defining this script file so that it runs when you open the plugin's ACP page?


  • Community Rep

    Not sure if it is proper, but I use define call with the page's route. I put this in my client.js.

    define('admin/plugins/plugin-id', function () { // 'admin/plugins/plugin-id' is the route for the admin page
        return { init: function(){
            // do stuff here, like call socket.emit, and setup settings as normal.
        }};
    });
    

    I usually require a separate module, so that the full script isn't loaded on every page load.

    define('admin/plugins/plugin-id', function () {
    	return { init: function () {
    		require(['/route/to/plugin/js/acp.js'], function (acp) {
    			acp.doThings();
    		});
    	}};
    });
    

    acp.js

    define(['settings', 'translator'], function (settings, translator) {
    
    	var acp = { };
    
    	acp.doThings = function () {
    		// This is where I would call socket.emit('mySocketEvent') so that I can get the additional data I need.
    	};
    
    	return acp;
    });
    

    I'm certain this is not the best way to do it, and the additional require is not necessary now that we have acpScripts now. There was some other reason I separated the scripts too, i don't remember at the moment.


  • Plugin & Theme Dev

    @yariplus how do I require modules (groups, users...) so I can use their methods?


  • Community Rep

    You can't call them directly from the client. I usually use socket.io, you define an event in your library file where you get the data, and then call it in the acp script.

    library.js

    var socketAdmin = module.parent.require('./socket.io/admin');
    var Groups = module.parent.require('./groups');
    var User = module.parent.require('./user');
    
    socketAdmin.yourplugin = {
    
      // This function is now exposed as the event 'admin.yourplugin.someevent'
      someevent: function (socket, data, callback) {
        // Use the data from the client to grab member objects.
        Groups.getMembers(data.groupName, data.start, data.stop, function (err, uids) {
            if (err) return console.log(err);
            User.getUsersData(uids, function (err, members){
                callback(null, {members: members});
            });
        });
      }
    
    };
    

    acp.js

    // Send the group name with the amount of members we want to the server.
    socket.emit('admin.yourplugin.someevent', {groupName: "GroupName", start: 0, stop: 200}, function (err, data) {
        // Log the response, should be an array of user objects.
        console.log(data.members);
    });
    

Log in to reply
 


Looks like your connection to NodeBB was lost, please wait while we try to reconnect.