Is there a way to attach a handler to any selection event?

Discussion in 'Mod Support' started by coldboot, May 2, 2015.

  1. coldboot

    coldboot Active Member

    Messages:
    447
    Likes Received:
    112
    I want to run some code every time a unit selection is made.

    So if I summon a control group with the '1' key, click on a unit, drag+select a unit, or press a hotkey to select idle fabbers, I want my code run with some context about the selection.

    Is there a selection event that I can hook on to?
  2. dom314

    dom314 Post Master General

    Messages:
    896
    Likes Received:
    1,196
    If model.selection is a knockout.js observable, then you can subscribe to it:
    Code:
    model.selection.subscribe(function(newValue) {
       // do stuff here
    });
    
    P.S. You may have to use the debugger to find out what the actual ko observable for the current selection is. model.selection is just a guess made from shoddy memory.
  3. cola_colin

    cola_colin Moderator Alumni

    Messages:
    12,074
    Likes Received:
    16,221
    This kind of code works in any scene, not just live_game:

    Code:
    (function() {
        var oldSelectionHandler = handlers.selection;
        handlers.selection = function(payload) {
            console.log("The selection was changed, the new selection is");
            console.log(payload);
           
            if (oldSelectionHandler) {
                oldSelectionHandler(payload);
            }
        };
    }());
    
    It's the general way to hook into any handlers for events:
    - get a reference to the old handler
    - overwrite the old handler
    - call the old handler in your new one
  4. coldboot

    coldboot Active Member

    Messages:
    447
    Likes Received:
    112
    Thanks guys, I figured it out:

    Code:
    #modinfo.json
    # ... snip
            "live_game": [
                "coui://ui/mods/mymod.js/live_game.js"
            ]
    # ... snip
    
    # ui/mods/mymod/live_game.js
    model.selection.subscribe(function (value) {
        console.log('selection made: ', value);
    }
    
  5. coldboot

    coldboot Active Member

    Messages:
    447
    Likes Received:
    112
    The handlers.selection method mentioned here doesn't distinguish between a completed selection (clicking or using a keybindings), versus a selection-in-progress (drawing a bandbox over units, but not letting go of the mouse button yet). But the model.selection.subscribe method does.

    Check this thread: Suspected UI bug: Clicking units produces "selectionResult", "Select Idle Fabbers" does not for more information.

Share This Page