【问题标题】:Aurelia Singleton View modelAurelia Singleton 查看模型
【发布时间】:2020-03-27 06:03:26
【问题描述】:

在 Aurelia 项目中,我有一个视图模型,我想在路由器导航之间保持状态。我认为将@singleton() 添加到我的视图模型类中可以实现这一点。

事实上,我已经创建了一个简单的 Aurelia 项目。我能够导航离开和返回到同一页面并保持状态。我的构造函数仅在我第一次导航到该页面时被调用。

import { singleton } from 'aurelia-framework';

@singleton()
export class Welcome {
  heading = 'Welcome to the Aurelia Navigation App!';

  constructor() {
      console.log('constructor');
  }

  activate() {
      console.log('activate');
  }

  attached() {
      console.log('attached');
  }
}

但是,在我较大的应用程序中,这不起作用。我添加了装饰器,并且在我第二次导航到该页面时仍会调用我的视图模型的构造函数。 (我什至把这个视图模型复制到我更大的应用程序中,它不被视为单例。)

显然,这两个项目之间肯定有一些不同。但是,我看不出有什么区别。是否有我设置的设置会覆盖@singleton() 的行为?

【问题讨论】:

标签: dependency-injection singleton containers aurelia


【解决方案1】:

原来解决方案是 jspm 更新。我曾认为删除我的 jspm_packages 并运行 jspm install 是等效的。但事实并非如此。

现在我的 Aurelia 模块是最新的,singleton() 装饰器可以正常工作。

【讨论】:

    【解决方案2】:

    您可能有多个单例自定义元素实例 - 根据定义,单例自身不能有多个实例。您想要的是一个创建一次并重复使用的视图模型。

    这是我成功使用的解决方案。这个想法是有一个构建一次的全局视图模型实例,并且有一个控制器视图使用它来组成视图/虚拟机。

    HTML

    <template>
      <require from="yourView.html"></require>
      <p> parentClass.html </p>
      <compose view="yourView.html" view-model.bind="singletonViewModel"></compose>
    </template>
    

    JS

    import { YourView } from 'yourView';
    export class parentClass {
      // constructor for parentClass will run multiple times.
      constructor() {
        /** this is the key, you must instantiate a custom view model once
         on some globally singleton object like window or global in Node */
        if ( typeof window.yourView === 'undefined' ) {
          window.yourView = new YourView();
        }
      }
    
      bind() {
        this.singletonViewModel = window.yourView;
      }
    }
    

    您在此视图模型中所做的一切现在都将在导航之间持续存在,并且构造函数只会被调用一次。单例视图模型的 attach() 和 detached() 仍将如您预期的那样激活。

    还请注意,您可以使用它来缓存可以在它们之间切换的视图模型的多个实例。我的应用程序有一个全局服务来跟踪多个虚拟机,这些虚拟机根据请求构建/返回虚拟机。这带来的好处是我可以在构造阶段进行一次繁重的处理,然后再也不用担心它了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-29
      • 2019-05-07
      • 2020-08-05
      • 2011-01-11
      • 2021-06-06
      • 2010-11-17
      • 2021-09-26
      相关资源
      最近更新 更多