Search code examples
javascriptrequirejsdurandalamdaurelia

Using AMD module as an Aurelia ViewModel


I was playing with Aurelia and seems pretty nice, I use Durandal for some projects and this definitively suit my needs.

Use the new class definition from EC6 is awesome. But now I'm preparing something in which I need to use a classic AMD modules with requireJs, something like this one:

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;
});

Following the Aurelia's documentation I found that is possible to use something like the testModule as a ViewModel, in fact that viewModel was used in a Durandal application.

But after some attempts I was unable to get this working.

Any thoughts or approaches that someone has followed to do that? And most important, it is possible? I think it is but just to confirm that are compatible.

Thanks.


Solution

  • We've been experimenting a bit with that. Here is what we came up with. The work is based on the Skeleton Navigation App:

    1. Create a folder amd in the projects root.
    2. Copy your original Durandal VM (from your example) as is into it.
    3. Create a Wrapper VM inside src named also testmodule.js with this contents:

      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. Enjoy :)

    What this does is essentially wrap your original DurandalVM and expose it as a new AureliaVM. Its just a starter and there are definitely certain things to look into like respecting Durandals LifeCycle etc. but it's a good start I guess