从视图模型中调用一个自定义属性方法

问题描述:

我有一个自定义属性和一个显示和隐藏一些HTML内容的方法,我将该属性附加到视图模型中的一个元素。从视图模型中调用一个自定义属性方法

如何从视图模型调用定制属性中定义的方法?

要访问自定义属性的视图模型,只需将该自定义属性第二次放在该元素上,但这次将.ref="viewModelPropertyName"置于该属性上。然后,在父视图模型中,您可以使用viewModelPropertyName(或您提供的任何名称)访问该属性上的方法。你可以在这里看到这样一个例子:https://gist.run/?id=9819e9bf73f6bb43b07af355c5e166ad

app.html

<template> 
    <require from="./has-method"></require> 

    <div has-method="hello" has-method.ref="theAttribute"></div> 

    <button click.trigger="callMethod()">Call method</button> 
</template> 

app.js

export class App { 
    callMethod() { 
    const result = this.theAttribute.someMethod('blah'); 
    } 
} 

有-method.js

export class HasMethodCustomAttribute { 
    someMethod(foo) { 
    console.log('someMethod called with foo = ' + foo + ', this.value = ' + this.value); 

    return `Hello ${foo}`; 
    } 
} 

有一些方法可以做到这一点,但我相信理想的做法是将属性从自定义属性绑定到视图模型。例如:

MyCustomAttribute { 

    @bindable showOrHide; //use this to show or hide your element 
} 

MyViewModel { 

    visible = false; 
} 

用法:

<div my-custom-attribute="showOrHide.bind: visible"></div> 

所以,当你改变你visible也会改变showOrHide

不过,好记住Aurelia路上已经有一个showif定制属性:

<div show.bind="visible" my-custom-attribute></div> 
<div if.bind="visible" my-custom-attribute></div> 

确保,如果你真的需要创建自定义属性此行为。

+0

这个答案不正确。我发布了正确的答案。 –

+1

@AshleyGrant我知道答案没有显示如何调用一个自定义属性方法,但是你不觉得从custom-attribute调用一个方法来隐藏/显示一个元素是完全矫枉过正的吗? –

+0

我完全同意你的看法。但与此同时,我在这里从我的“接受答案”啤酒中啜饮,而且味道很不错。:-) –

这可以不需要ref来完成。这是一个例子,显示了如何。

它使用自定义属性从自定义元素的自定义属性上调用showNotification方法。

在自定义属性:

@bindable({ defaultBindingMode: bindingMode.twoWay }) showNotificationCallback:()=> void; 

bind() { 
    this.showNotificationCallback = this.showNotification.bind(this); 
} 

showNotification() { 
    // Your code here 
} 

在定制元素视图(注意在此该值不存在括号的结合):

<div notification="show-notification-callback.bind: showSaveSuccessNotification;></div> 

在定制元素视图模型:

// Show the save success view to the user. 
if (typeof this.showSaveSuccessNotification=== 'function') { 
    this.showSaveSuccessNotification(); 
}