簡體   English   中英

使用AMD模塊作為Aurelia ViewModel

[英]Using AMD module as an Aurelia ViewModel

我當時在與Aurelia一起玩,看上去還不錯,我在某些項目中使用了Durandal,這絕對滿足了我的需求。

從EC6使用新的類定義非常棒。 但是現在,我正在准備一些需要將經典AMD模塊與requireJs配合使用的東西,如下所示:

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,實際上在Durandal應用程序中使用過viewModel。

但是經過一些嘗試,我無法使它正常工作。

有人遵循此想法或方法嗎? 最重要的是,有可能嗎? 我認為這只是為了確認是否兼容。

謝謝。

我們已經對此進行了一些試驗。 這就是我們想出的。 這項工作基於Skeleton Navigation App:

  1. 在項目根目錄中創建一個文件夾amd
  2. 將原始的Durandal VM(從您的示例中)原樣復制到其中。
  3. src創建一個包裝虛擬機,也名為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等。但這是一個不錯的開始

這是與Aurelia一起使用的AMD模塊示例

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源文件生成的

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存儲庫中的示例說明進行操作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM