javascript - 无法从 <content> 元素调用 View 模型中的函数

标签 javascript html aurelia aurelia-dialog aurelia-templating

当我点击按钮 #btn1#btn2 保存时,控制台显示:

Uncaught Error: save is not a function
    getFunction @ aurelia-binding.js:1971
    evaluate @ aurelia-binding.js:1565
    callSource @ aurelia-binding.js:4989
    (anonymous function) @ aurelia-binding.js:5013
    handleDelegatedEvent @ aurelia-binding.js:3211

但是外部按钮 #btn3 工作正常。我也在 $parent.save() 中尝试了 #btn2,但它不起作用。有什么想法吗?

app.html

<create-location contact.two-way="contact" working-time.two-way="workingTime">
    <require from="dist/component/working-time"></require>
    <working-time title="Working Time" view-model.ref="workingTime"></working-time>
    <require from="dist/component/contact"></require>
    <contact title="Contact" phone="123" email="user@example.com" fax="123456" view-model.ref="contact"></contact>

    <button id="btn1" type="button" click.delegate="save()">Save (=>error<=)</button>
    <button id="btn2" type="button" click.delegate="$parent.save()">Save (=>error also<=)</button>
</create-location>

创建位置.html

<template>
    <button id="btn3" type="button" click.delegate="save()">Save (=>it works<=)</button>
    <content></content>
</template>

创建位置.js

import {bindable} from 'aurelia-framework'

export class CreateLocationCustomElement {
    @bindable contact;
    @bindable workingTime;

    save() {
        alert("save");
    }
}

更新 我尝试了 Fabio 的建议和 it works

另一个问题:看看 aurelia dialog ,他们在 testDelegate 元素内调用 view-model 的 <content> 函数,类似于我的情况。他们不使用 view-model.ref 。我查看了源代码,但没有找到他们处理该调用的位置。也许我错过了一些要点或者这里有约定。有谁知道他们是怎么做到的?

最佳答案

您可以使用 view-model.ref 将创建位置的 View 模型放入属性中,然后使用该属性调用 save() 。像这样:

<create-location view-model.ref="createLocationVM" contact.two-way="contact" working-time.two-way="workingTime">
    <require from="dist/component/working-time"></require>
    <working-time title="Working Time" view-model.ref="workingTime"></working-time>
    <require from="dist/component/contact"></require>
    <contact title="Contact" phone="123" email="user@example.com" fax="123456" view-model.ref="contact"></contact>

    <button id="btn1" type="button" click.delegate="createLocationVM.save()">Save (=>error<=)</button>

</create-location>

不过,我认为重新创建整个组件会更好。无需在组件内容中使用 <require>,也许您可​​以将第二个保存按钮放在创建位置的 View 中。

关于javascript - 无法从 <content> 元素调用 View 模型中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37608119/

相关文章:

javascript - rails + Javascript : How do I create a button that slides/changes a form from left to right?

JavaScript:如何生成随机字母表,其中某些单词随机隐藏?

奥里莉亚组成

javascript - 如何制作标题和第一列固定在垂直和水平滚动条上的表格?

javascript - 使用 Javascript 将列表值发送到文本框

css - 如何在sidenav materializecss上添加边距底部?

jquery - 优雅地回退到移动设备上的普通文件 uploader (Windows 移动问题)

Aurelia 验证规则 : Unable to parse accessor function

javascript - 类型错误 : Object doesn't support property or method 'entries' (IE11)

javascript - 正确使用异步(使用 forEach)