Search code examples
ractivejs

Calling custom method from another custom method


When a custom method invokes another custom method, any this.get() references in the 2nd method will fail. Here's a simple example (or full JSFiddle here):

var ractive = Ractive({
    ...
    data: {
        Title: "Just an example",

        Method1: function() { return this.get("Title"); },
        Method2: function() { return this.get("Method1")(); }
    }
});
....

<div id="template">
    {{ Method1() }}   <!-- This works. It outputs "Just as example" -->
    {{ Method2() }}   <!-- This throws an error -->
</div>

Invoking Method1() on its own works fine but it fails when invoked by Method2(). The error is "undefined is not a function" because this.get() is undefined in this context.

What's the proper way to do this?


Solution

  • I think, you need to pass on context when calling that method:

    Method2: function() { return this.get("Method1").call(this); }
    

    Demo: http://jsfiddle.net/aq4w3okr/5/