【问题标题】:Global Functions In AureliaAurelia 中的全局函数
【发布时间】:2015-08-18 08:01:00
【问题描述】:

我试图弄清楚如何在 Aurelia 中存储类似“全局”的函数。我已经按照本教程“http://blog.durandal.io/2015/04/24/aurelia-custom-elements-and-content-selectors/”打开了一个带有动态视图模式的模式,但我不知道我应该把这个函数放在哪里,所以我可以重用我的所有视图路线。

我在默认视图中创建了这个函数:

//open modal
setModal(modal) {
    this.contentModal = modal;
    $('.modal').modal();
}

在该视图模板中使用此标记:

<a click.delegate="setModal('users')">Test</a> <a click.delegate="setModal('child-router')">Test 2</a>
<modal>
    <modal-header title.bind="'View Person'"></modal-header>
    <modal-body content.bind="contentModal"></modal-body>
    <modal-footer buttons.bind="['Cancel']"></modal-footer>
</modal>

我可以在该视图模板中通过click.delegate="setModal('users') 调用它,但我无法弄清楚如何在该视图模板之外实际使用它。

对不起,我对这个框架很陌生!

【问题讨论】:

    标签: javascript aurelia


    【解决方案1】:

    所以听起来你有一个默认视图 + 视图模型,我们称它们为 app.html 和 app.js。

    在 app.html 中有模态标记:

    <modal>
        <modal-header title.bind="'View Person'"></modal-header>
        <modal-body content.bind="contentModal"></modal-body>
        <modal-footer buttons.bind="['Cancel']"></modal-footer>
    </modal>
    

    在 app.js 中,您可以显示模式:

    //open modal
    setModal(modal) {
        this.contentModal = modal;
        $('.modal').modal();
    }
    

    您的问题是“我如何与其他视图模型共享 setModal 函数?”

    您可以在容器中注册 setModal 函数。然后你就可以将它注入到其他依赖于该函数的视图模型中:

    app.js

    import {inject, Container} from 'aurelia-framework'; // or 'aurelia-dependency-injection'
    
    @inject(Container)
    export class App {
      constructor(container) {
        // register the setModal function in the container
        // under the key "setModal".
        container.registerInstance('setModal', this.setModal.bind(this));
      }
    
      //open modal
      setModal(modal) {
        this.contentModal = modal;
        $('.modal').modal();
      }
    }
    

    some-other-view-model.js

    import {inject} from 'aurelia-framework'; // or 'aurelia-dependency-injection'
    
    @inject('setModal') // inject the setModal function into this view-model
    export class SomeOtherViewModel {
      constructor(setModal) {
        // create a setModal property for binding purposes
        this.setModal = setModal;
      }
    }
    

    也许值得看看aurelia-dialog 插件。您也可以将其包装在自定义属性中,这样您就不必将 setModal 函数导入您的视图模型。

    【讨论】:

    • 非常感谢您的款待,将查看自定义属性!
    【解决方案2】:

    我建议在您的配置中使用globalResources 函数。

    一个例子是

    export function configure(aurelia) {
      aurelia.use
        .standardConfiguration()
        .globalResources('scripts/global.js');
    
      aurelia.start().then( () => aurelia.setRoot('main.js'));
    }
    

    【讨论】:

      猜你喜欢
      • 2020-03-18
      • 1970-01-01
      • 2016-10-06
      • 2015-09-29
      • 2019-03-02
      • 2013-05-23
      • 2012-08-08
      • 2015-06-13
      • 2020-07-16
      相关资源
      最近更新 更多