ECMA: Find out, if trigger was cron or triggereditem?

I have a rule, which usually fires, when a item was triggered, but I also like to cron that rule. As the rule already triggers, when the underlying item could be in the old state, so I’d like to do something like this:

if (typeof(event) === undefined) {
  // Take the item, if rule was cron-triggered
  var sonnenphase = items["AstronomischeSonnendatenPL12_Sonnenphase"];
} else {
  // take the itemCommand, if the rule was item-triggered
  var sonnenphase = event.itemCommand;
}

But the logs give me this:

2021-01-21 09:18:22.637 [ERROR] [internal.handler.ScriptActionHandler] - Script execution of rule with UID 'AstroDarkness' failed: ReferenceError: "event" is not defined in <eval> at line number 6

which is precisely, what I’d like to have! :wink:
what should I do event == undefined also doesn’t work…

if(this.event === undefined)

might work.

But beware, it might not work for an unexpected reason. Everything in this gets reused every time the script is run. This is great as it gives us a way to preserve stuff between runs of the rule. But it means that once the rule is triggered by an Item once, this.event might always be defined from that point onwards. So the test would only work that first time.

I’ve never done this so I don’t know the behavior.

One thing that might work to get around this is to make the last line of the rule reset this.event to null or undefined.

But the big trick here is that JavaScript appears to let you test if a variable is defined on some Object (in this case this), but it doesn’t let you do the same on variables in general (i.e. event without the this.). Since this.event and event are essentially the same thing we can get around the limitation.

1 Like

A couple of days ago I was wondering why the rules with multiple triggers where not running at the specified cron intervals.

after some testing and troubleshooting I found out that

if((typeof event) == 'undefined'){

works for me :slight_smile:

2 Likes

If the rule is triggered by an item command the type of event will be org.openhab.core.items.events.ItemCommandEvent

work both for me, too! thanks!

Just a heads up: If you use multiple triggers like I do, be aware that this rule will only work until it is triggered by an item :frowning:

@rossko57 warned me but I forgot about it :innocent:

So untill this is fixed I think I’m going to split my rules into a time driven and a “item” driven one.

You can “unset” event as the last line of the rule.

this.event = undefined;
2 Likes

Do’h!

Thanks, that works for both event and this.event!

Is there a difference between event and this.event?

No. I like to always use this by convention when posting to the forum to make it explicit to the reader that the variable is set in the context.