使用 AMD 模块作为 Aurelia ViewModel

Using AMD module as an Aurelia ViewModel

我在玩 Aurelia,看起来很不错,我在一些项目中使用 Durandal,这绝对符合我的需要。

使用来自 EC6 的新 class 定义很棒。但是现在我正在准备一些东西,我需要在其中使用带有 requireJs 的 classic AMD 模块,就像这样:

define("testModule",
[],
function() {
    "use strict";
    console.log('testModule loaded');

    var testModule = function() {
        var that = this;

        this.variable = 10;

        that.getVariable = function(){
            alert('function executed ' + that.variable);
        };
    }

    return testModule;
});

根据 Aurelia 的文档,我发现可以将 testModule 之类的东西用作 ViewModel,事实上,viewModel 已用于 Durandal 应用程序。

但经过一些尝试后,我无法使它正常工作。

有人遵循了哪些想法或方法来做到这一点? 最重要的是,这可能吗?我认为是,只是为了确认是否兼容。

谢谢。

这是与 Aurelia 一起使用的 example AMD module

define(["require", "exports"], function (require, exports) {
  var Welcome = (function () {
    function Welcome() {
      this.heading = "Welcome to the Aurelia Navigation App (VS/TS)!";
      this.firstName = "John";
      this.lastName = "Doe";
    }
    Object.defineProperty(Welcome.prototype, "fullName", {
      get: function () {
        return this.firstName + " " + this.lastName;
      },
      enumerable: true,
      configurable: true
    });
    Welcome.prototype.welcome = function () {
      alert("Welcome, " + this.fullName + "!");
    };
    return Welcome;
  })();
  exports.Welcome = Welcome;
});

它实际上是由 TypeScript source file

生成的
export class Welcome {
  public heading: string;
  public firstName: string;
  public lastName: string;

  constructor() {
    this.heading = "Welcome to the Aurelia Navigation App (VS/TS)!";
    this.firstName = "John";
    this.lastName = "Doe";
  }

  get fullName() {
    return this.firstName + " " + this.lastName;
  }

  welcome() {
    alert("Welcome, " + this.fullName + "!");
  }
}

您可以按照 GitHub 存储库中的 the sample's instructions 来使用示例。

我们对此进行了一些试验。这是我们想出的。作品基于骷髅导航App:

  1. 在项目根目录中创建文件夹 amd
  2. 将您的原始 Durandal VM(来自您的示例)原封不动地复制到其中。
  3. src 中创建一个 Wrapper VM,同样命名为 testmodule.js,内容如下:

    export class TestModule {
      constructor() {
      }
    
      activate() {
        return System.import('../amd/testmodule').then( (result) => {
          if(typeof result === 'function')
            Object.assign(this, new result());
          else
            Object.assign(this, result);
        });
      }
    }
    
  4. 尽情享受吧:)

这实际上是包装您的原始 DurandalVM 并将其公开为新的 AureliaVM。它只是一个开始,肯定有一些事情需要研究,比如尊重 Durandals LifeCycle 等。但我想这是一个好的开始