Knack, under the hood - how to invoke a Display Rule programmatically?

Hi guys,

Does anyone know if it’s possible to invoke a Display Rule programmatically, using Javascript?

I have this rule in a scene that hides a view conditionally, but I’d like to apply it without having to do a full page reload.

image

Thanks,
Normand

I would recommend calling Knack.router.scene_view.render() to re-render the page with the latest rules applied.

Rendering previously hidden views after the page has already rendered will result in weird behavior like broken layout or views rendering at the bottom of the page instead of in the correct order. If you only want to hide already rendered views based on page rules, you can use the following:

const sceneView = Knack.router.scene_view;
sceneView.checkPageRules(() => {
  sceneView.views_ignore.forEach((viewKey) => {
    const view = Knack.views[viewKey];
    view?.$el?.remove();
  });
});

If you want to retrieve just the page rule keys, you can also call the async processServerRules function:

/** @type {string[]} */
const ruleKeys = await Knack.router.scene_view.processServerRules(Knack.router.scene_view.model.get('key'));```
1 Like

Hi David,

Thank you for your answer.
Finally, I opted for this solution:

Knack.router.scene_view.render();

It’s a bit slow to render everything, but it’s simple, clean and definitely faster than a full page reload. Also, as you pointed out, it prevents any potential layout problems.

This opens the door to a new set of KTL features I had in mind for a while.

Norm

1 Like