问题
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.
回答1:
We've been experimenting a bit with that. Here is what we came up with. The work is based on the Skeleton Navigation App:
- Create a folder
amd
in the projects root. - Copy your original Durandal VM (from your example) as is into it.
Create a Wrapper VM inside
src
named alsotestmodule.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); }); } }
- 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
回答2:
Here is an example AMD module that works with Aurelia:
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;
});
it was actually generated by a 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 + "!");
}
}
you can follow the sample's instructions in the GitHub repository to work with the sample.
来源:https://stackoverflow.com/questions/28335502/using-amd-module-as-an-aurelia-viewmodel