Register an Action with Javascript

  • 1
  • Question
  • Updated 2 years ago
  • Answered
Is there a way to register an action to a model from javascript? 
Photo of Velvel Marasow

Velvel Marasow

  • 452 Points 250 badge 2x thumb

Posted 2 years ago

  • 1
Photo of mB Pat Vachon

mB Pat Vachon, Champion

  • 42,704 Points 20k badge 2x thumb
Hmmm ... don't understand why you'd need to, but I don't think any action framework can be registered from javasript. What's the use case? You can setup an action on model using model actions.



Alternatively, you could use our Custom Compenent called "Template w/ Action Framework and Context" to store Action Framework and call it using Javascript.
Photo of Velvel Marasow

Velvel Marasow

  • 452 Points 250 badge 2x thumb
Well I needed it because I was working on a component that integrated with a model already existing on the page, and I needed to set a action on the "model.loaded" event.
Eventually found a hack for it injecting the action into the model and re-initializing it:
model.actions = model.actions || [];
var action = {
    actions: '<actions><action type="publish" event="' + eventName + '"/></actions>',
    events: ["models.loaded"]
};	
model.actions.push(action);

model.initialize({}); 
(Edited)
Photo of mB Pat Vachon

mB Pat Vachon, Champion

  • 42,704 Points 20k badge 2x thumb
Well that was nifty!
Photo of Barry Schnell

Barry Schnell, Champion

  • 18,076 Points 10k badge 2x thumb
Nifty indeed, however I'm not sure taking this approach would be best.  At the very least, it would likely be an unsupported scenario.

Velvel -

If I'm understanding what your goal is, you want something to happen when a model is loaded.  You can accomplish this by subscribing to the models.loaded event from within your component using the skuid.events.subscribe api.  In this manner, you're component is in control and doesn't rely directly modifying the underlying model data structure.  Unless absolutely necessary, skuids data structures shouldn't be directly manipulated.
skuid.events.subscribe('models.loaded', function(data) {              
       // do something
});

If you have the above code run from within your component, your component will get notified every time a model is loaded.  The params passed give you which model, etc. so you can have conditional logic on if/when you should do certain things.

The one thing to note with the above is that if your component is conditionally rendered, your "render" method will get called multiple times within a page lifetime so you'll want to make sure you unsubscribe when unrendered to avoid duplicate notifications.