在Aurelia中使用AMD / Require模块

时间:2017-07-13 15:17:29

标签: javascript aurelia durandal aurelia-cli

我们正在考虑将我们的Durandal应用程序更新到Aurelia(最后)。我们现在最关心的是代码重用。我们将为视图逻辑编写TypeScript,但是有很多复杂的客户端媒体访问(webRTC的东西)需要花费大量时间才能用作原始的JavaScript AMD模块。

我见过有关使用AMD ViewModels的问题;我问的是在新的aurelia视图模型中使用AMD模块。

作为一个简单的例子,我有一个mediaDeviceScanner.js模块:

define(["modules/logger"], function (logger) {
    'use strict';
    const mediaDeviceScanner = {};

    mediaDeviceScanner.scanDevices = function() {
        return navigator.mediaDevices.getUserMedia({video:true}).then(function(stream) {
            return stream;
        }).then(function(stream) {
            return navigator.mediaDevices.enumerateDevices().then(function (availableDevices) {
                const mediaDevices = [];
                for (let i = 0; i < availableDevices.length; ++i) {
                    const deviceCandidate = availableDevices[i];
                    if ((deviceCandidate.kind === "videoinput") && deviceCandidate.deviceId != "default" && deviceCandidate.deviceId != "communications") {
                        mediaDevices.push({ label: deviceCandidate.label, kind: (deviceCandidate.kind == "videoinput" ? "Camera " : "Microphone ") + (mediaDevices.length + 1), id: deviceCandidate.deviceId });
                    }
                }
                return mediaDevices;
            }).catch(function (error) {
                logger.log(error, logger.logLevels.warning, logger.features.webcam, logger.features.webcam);
            });
        })
    }

    return mediaDeviceScanner;
});

在aurelia视图模型中调用mediaDeviceScanner.scanDevices的快乐路径是什么?

在我的Durandal vm中,我有这个:

define(["amd/mediaDevices/mediaDeviceScanner"],function(mediaDeviceScanner){
    mediaDeviceScanner.scanDevices().then(function(devices){alert('woot')});
});

在评估“框架转换”成本之前,我想先了解一下“再利用成本”会是什么样的。

1 个答案:

答案 0 :(得分:3)

关于这个话题有一个老问题。 Using AMD module as an Aurelia ViewModel 它基本上归结为您正在使用的装载机。 Aurelia CLI默认使用requirejs,但最近获得了支持SystemJS的更新。有了它,就像在引用的问题中所描述的那样,可以为现有代码创建包装器。包装器可能非常薄,甚至可以推广以节省大量样板

- EDIT-- 出于兴趣,我很快就尝试了一个基于SystemJS的新CLI项目。

  1. 脚手架后,我已将您的示例模块放在9200025803572390001691385 9200025803572390001691393
  2. 删除了记录器依赖项,因为它未在您的示例中提供
  3. 转到scripts/amd/media-device-scanner.js并在构造函数内添加以下代码:
  4. src/app.js

    仍然像魅力一样;)