Search code examples
templatesscopethisdust.js

dust.js losing 'this' context in handlers?


I have a [seemingly] trivial dust.js template. The context object I am using to render the template contains a handler which references another item in the context object. I also include a toString handler, which also references another item in the context object.

Template:

{error}
<pre>
{#error.getStackTrace}
{.}{~n}
{/error.getStackTrace}
</pre>

Context:

{
  error: {
    st: ['a','b','c'],
    msg: 'This is an error message',
    getStackTrace: function () {
      return this.st;
    },
    toString: function () {
      return this.msg;
    }
  }
}

Rendered:

This is an error message<pre></pre>

If I reference {#error.st} directly, it renders correctly:

This is an error message<pre>a
b
c
</pre>

If I inspect 'this' inside of the getStackTrace() handler, it is pointing back to DOMWindow. It is interesting, however, that invoking toString() implicitly, it is scoped correctly. If I explicitly invoke toString() {error.toString}, then the scope jumps back to DOMWindow.

The only reason this is a problem, (why I cannot access error.st directly) is because the st array is actually stored in a Qooxdoo property, and I only have access to the generated getter. The above example mimics the actual object as simply as I can.

Is this a bug in dust.js? Is it losing the correct scope in handlers? Or am I missing something in the dust.js docs to retain scope?


Solution

  • you could use it in this way:

    {
     error: {
       st: 'a,b,d',
       msg: 'This is an error message',
       getStackTrace: function (chunk, context) {
         return context.current().error.st;
       },
       toString: function () {
         return this.msg;
       }
     }
    }