【问题标题】:Cannot call function in view model from <content> element无法从 <content> 元素调用视图模型中的函数
【发布时间】:2016-10-03 03:36:55
【问题描述】:

当我点击按钮 #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 工作正常。我也在#btn2 中尝试$parent.save(),但它不起作用。有什么想法吗?

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>

create-location.html

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

create-location.js

import {bindable} from 'aurelia-framework'

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

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

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

另一个问题:看看aurelia dialog,他们在&lt;content&gt; 元素中调用testDelegate 的视图模型函数,类似于我的情况。他们不使用view-model.ref。我看了一下源代码,但我不知道他们在哪里处理该调用。也许我错过了一些观点或者这里有约定。有谁知道他们是怎么做到的?

【问题讨论】:

    标签: javascript html aurelia aurelia-dialog aurelia-templating


    【解决方案1】:

    您可以使用view-model.ref 将创建位置的视图模型放入一个属性中,然后使用该属性调用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>
    

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

    【讨论】:

    • 因为创建位置页面是服务器上的预渲染页面,我希望 aurelia 控制浏览器上的整个页面(使用绑定、自定义组件等),所以我创建了 @ 987654327@ 组件并使用 aurelia 增强功能 (view more here)。我想知道这是否是正确的做法。你有没有做过这样的事情?顺便说一句,看看aurelia dialog。他们有一个testDelegate 函数,但我不知道该怎么做。他们根本不使用view-model.ref
    猜你喜欢
    • 1970-01-01
    • 2023-03-28
    • 2013-10-31
    • 1970-01-01
    • 2014-11-20
    • 1970-01-01
    • 2015-05-12
    • 1970-01-01
    • 2013-02-03
    相关资源
    最近更新 更多