Durandal给出了"无法读取属性' nodeType' of null"错误

时间:2015-01-22 00:49:28

标签: knockout.js durandal

一直在玩Durandal 2.1.0,但似乎无法在跑步中得到一个例子。当我在Chrome中运行时,我收到错误"无法读取属性' nodeType' of null"。

文件夹结构是: -viewmodels

| -vm1.js

-Scripts

| -durandal ...

-views

| -vm1.html

-Index.html

的index.html

<html>
<head>
    <title></title>
    <script src="Scripts/knockout-3.1.0.js"></script>
    <script src="Scripts/jquery-1.9.1.js"></script>
</head>
<body>
<script src="Scripts/require.js" data-main="Scripts\main"></script>
</body>
</html>

main.js

requirejs.config({
paths: {
    'text': 'Scripts/text',
    'durandal': 'Scripts/durandal',
    'plugins': 'Scripts/durandal/plugins',
    'viewLocator': 'durandal/viewLocator',
}
});

define('jquery', function () { return jQuery; });
define('knockout', ko);

define(function (require) {
    var system = require('durandal/system'),
        app = require('durandal/app'),
        router = require('plugins/router');

    system.debug(true);

    app.start().then(function () {
    app.setRoot('viewmodels/vm1');
});
});

vm1.js:

define(['plugins/router'], function (router) {
    return {
        router: router,
        activate: function () {
            //This line never fires
            alert();
        }
    }
});

PS:与n​​uget一起安装。假设任何JS错误都是拼写错误,脚本本身就可以了。我尝试了各种方式移动脚本加载的顺序,使用viewLocator手动定义路径。似乎与我在Durandal网站上看到的例子完全一致。

任何帮助表示感谢。

2 个答案:

答案 0 :(得分:2)

所以,我已经和Durandal / Knockout玩了一段时间了,我在开始时遇到了类似的问题。如果您已经开始在您的应用中使用Knockout,那么所有其他答案都很有用且更具相关性。但是因为我在使用Knockout之前就遇到了这个错误,所以我对代码进行了逐行细分。

事实证明,我没有在index.html文件中添加div#applicationHost元素。就是这样。简单地添加它就解决了我的问题。

的index.html

<body>
  <div id="applicationHost">
    ...
  </div>
</body>

现在,并非总是需要一个带有此ID的div,但是您必须手动编写应用程序。您可以在this discussion here上阅读更多内容。

答案 1 :(得分:1)

除非您直接指定路径或使用自定义viewLocator,否则您需要将 views 目录和 viewmodels 目录放在同一级别上。换句话说,他们需要成为树中的兄弟姐妹。

查看 main.js 中的主要切入点。我删除了无关的位:

function (system, app, viewLocator, bindings, extenders, validations) {
    //>>excludeStart("build", true);
    system.debug(true);
    //>>excludeEnd("build");        

    //Initialize KnockoutJS customizations
    bindings.init();
    extenders.init();        

    app.title = 'Some Application';

    app.configurePlugins({
        router: true,
        dialog: true,
        widget: true
    });

    app.start().then(function() {
        //Replace 'viewmodels' in the moduleId with 'views' to locate the view.
        //Look for partial views in a 'views' folder in the root.
        viewLocator.useConvention();

        //Show the app by setting the root view model for our application with a transition.
        app.setRoot('viewmodels/shell');
    });
});

我无法看到您拨打viewLocator.useConvention()的位置,或以其他方式自定义viewLocator

此外,您的 App 目录在哪里?我们有以下(在许多其他目录中):

  

应用

     
    

视图

         

的ViewModels

  

App 位于服务器上我们Web项目的顶层。