从另一个自定义方法调用自定义方法
Calling custom method from another custom method
当自定义方法调用另一个自定义方法时,第二个方法中的任何 this.get()
引用都将失败。这是一个简单的例子 (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>
单独调用 Method1()
工作正常,但在被 Method2()
调用时失败。错误是 "undefined is not a function" 因为 this.get()
在此上下文中未定义。
执行此操作的正确方法是什么?
我认为,调用该方法时需要传递上下文:
Method2: function() { return this.get("Method1").call(this); }
当自定义方法调用另一个自定义方法时,第二个方法中的任何 this.get()
引用都将失败。这是一个简单的例子 (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>
单独调用 Method1()
工作正常,但在被 Method2()
调用时失败。错误是 "undefined is not a function" 因为 this.get()
在此上下文中未定义。
执行此操作的正确方法是什么?
我认为,调用该方法时需要传递上下文:
Method2: function() { return this.get("Method1").call(this); }