A handy method every plugin should have...

For developers using the Construct 2 Javascript SDK

Post » Wed Sep 18, 2013 9:27 pm

This has been super useful for me.

[CODE]instanceProto.fire = function(eventName)
{
    this.runtime.trigger(cr.plugins_.MyPlugin.prototype.cnds[eventName], this);
};[/CODE]

This function allows for easy firing of conditions. For example, if you have a condition

[CODE]Cnds.prototype.OnError = function()
{
    return true;
};[/CODE]

You can, from basically anywhere, fire that condition with a call to
[CODE]this.fire("OnError");[/CODE]
or, from within an anonymous embedded method
[CODE]var self = this;
somelibrary.AsynchronousCall().then(
    function(result)
    {
        self.status = JSON.stringify(result);
        self.fire("OnSuccess");
    },
    function(result)
    {
        self.status = JSON.stringify(result);
        self.fire("OnError");
    });[/CODE]

The fire method could be made safer with a check that the event exists, but the above is the simplest form. I would suggest adding this to the template files for plugins and behaviors. What do others think?
B
6
S
1
Posts: 22
Reputation: 446

Post » Wed Sep 18, 2013 9:37 pm

As an addendum, in the plugin I'm working on now, I have the following set up:

[CODE]
instanceProto.setError= function(errorString)
{
    this.status.lastError = errorString;
    this.runtime.trigger(cr.plugins_.MyPlugin.prototype.cnds.OnError, this);
}

instanceProto.fire = function(eventName)
{
    if (cr.plugins_.MyPlugin.prototype.cnds[eventName])
    {
        this.runtime.trigger(cr.plugins_.MyPlugin.prototype.cnds[eventName], this);
    }
    else
    {
        this.setError("Condition " + eventName + " not found");
    }
};
[/CODE]

then I can set up an event that OnError prints out the error message. Of course, it may be better in other situations to log to the javascript console instead of (or in addition to) the above, but I found it handy, so I thought I'd pass on the tip.coatesjetset2013-09-18 21:37:51
B
6
S
1
Posts: 22
Reputation: 446


Return to Javascript SDK

Who is online

Users browsing this forum: No registered users and 0 guests