Durandal中哪个RequireJS语法正确?

时间:2013-03-25 16:18:17

标签: requirejs durandal

我对Durandal很新,但考虑到我在jQuery中的背景和一点KnockoutJS,认为这是一个很好的框架,但是我遇到了两种不同的使用RequireJS和Durandal的方法。

在Durandal样本中使用以下语法: Durandal / App / samples / modal / index.js

    define(['durandal/app', './customModal'], function (app, CustomModal) {

    return {
        showCustomModal: function() {
            app.showModal(new CustomModal()).then(function(response) {
                app.showMessage('You answered "' + response + '".');
            });
        }
    };
});

这里依赖关系/要求(这里是正确的词?)被定义为定义(['durandal/app', './customModal'])调用的第一个参数。

在Durandal文档中使用以下语法:Creating a Module

define(function(require){
  var backend = require('backend');

  return {
    customers:ko.observableArray([]),
    activate:function(){
      var that = this;
      return backend.getCustomers().then(function(results){
        that.customers(results);
      });
    }
  };
});

这里只将函数传递给define来定义,其中require作为该函数的依赖/需求。然后调用require函数以获得所需的实际依赖性/需求(var backend = require('backend');)。

来自.net IoC背景,第一个似乎是正确的,定义我的要求,让requirejs框架为我找到依赖项,第二个似乎是服务定位器反模式。

我对这两种方法的解释是否正确,如果使用第一种方法,文档是错误的(!)?

如果没有,这两种方法的优缺点是什么?哪一个是可取的,为什么?

非常感谢

2 个答案:

答案 0 :(得分:3)

我认为无论你最喜欢哪种方式都是要走的路。我认为requirejs是这样做的,所以你可以两种方式,所以它可以支持commonjs module format

根据requirejs的网站,如果您使用durandal解析其依赖关系的方式:

define(function(require) { var app = require('durandal/app');  app.start(); }

“这个包装器依赖于Function.prototype.toString()来提供函数内容的有用字符串值。这在某些设备上不起作用,比如PS3和一些旧的Opera移动浏览器。” - quoted from requirejs

但这是一个边缘案例,我认为没有太多人关心。除此之外......我会挑选最适合你的人。

我不确定服务定位器反模式的含义。我很确定这两种方式都是有效的,无论如何你选择这样做纯粹是为了美学。

修改**

Durandal不再使用上述模式来解析其依赖关系。它现在使用这种方式:

define(['./app','./system'], function (app, system) { //... });

答案 1 :(得分:0)

两种方式都是正确的。请查看Require JS文档。 Durandal JS基于JQuery,Knockout和RequireJS构建。浏览此博客文章。 http://dilanarandara.blogspot.com/2013/03/spa-with-durandaljs.html。您将了解Durandal JS以及如何使用它。