【问题标题】:Cannot construct the Router in Backbone app无法在 Backbone 应用程序中构建路由器
【发布时间】:2014-12-07 21:27:28
【问题描述】:

我正在构建一个 application with the fiddle here 用于使用 Backbone 和 node.js express 和 mongodb 进行自学。

我在构建通过从 Backbone.Router 扩展定义的路由器时遇到问题。

在 js 控制台我有错误消息:

[Error] TypeError: undefined is not a function (evaluating 'n.replace')
    template (underscore-min.js, line 5)
    global code (app.js, line 17)
[Error] TypeError: undefined is not a constructor (evaluating 'new appRouter()')
    (anonymous function) (localhost, line 79)
    j (jquery.min.js, line 2)
    fireWith (jquery.min.js, line 2)
    ready (jquery.min.js, line 2)
    I (jquery.min.js, line 2)
[Error] Failed to load resource: the server responded with a status of 404 (Not Found) (jquery.min.map, line 0)
[Error] Failed to load resource: the server responded with a status of 404 (Not Found) (backbone-min.map, line 0)
[Error] Failed to load resource: the server responded with a status of 404 (Not Found) (underscore-min.map, line 0)

正如我所检查的,我没有任何语法错误。在我使用的 jQuery .ready() 别名加载 app.js 后,是否不能确保执行我的入口点脚本?

我在这里错过了什么?

public/app.js

    _.templateSettings = {
     interpolate: /\{\{(.+?)\}\}/g
};
//Define Models, Collections, Views 
var postModel = Backbone.Model.extend({

});

var postsCollection = Backbone.Collection.extend({
    model: postModel,
    url: "/posts"
});

var postsListView = Backbone.View.extend({
    main: $('body'),
    collection: postsCollection,//! May be collection must be created to use in view.
    template1: _.template( $('#postsListTemplate') ),
    template2: _.template( $('#postsListItemTemplate') ),

    initialize: function(){
        this.render();
        this.collection = new postsCollection();
        this.collection.fetch();
        this.collection.on('add', this.renderPostsListItem, this);
    },

    render: function(){
        this.main.html( this.template1() );
        return this;
    },

    renderPostsListItem: function(){
        this.collection.forEach(function(each){
            this.$el.append( this.template2(each) );
        });
        return this;
    }
});


//Define Client-Side Routes
var appRouter = Backbone.Router.extend({
    routes: {
        "": "viewPosts",
    },

    viewPosts: function(){
        this.postslistview = new postsListView();
    },
});

views/index.ejs

<html>
    <head>
    <!--Templates-->

        <!--Post Templates-->
        <script type="text/template" id="postsListTemplate">
            <h1>Blog</h1>
            <h2>All Posts</h2>

            <ul></ul>
        </script>

        <script type="text/template" id="postsListItemTemplate">
            <li>{{title}}</li>
        </script>

        <script type="text/template" id="postTemplate">
            <a href="/">All Posts</a>

            <h3>{{title}}</h3>
            <p>{{pubDate}}</p>
            <p>{{content}}</p>

            <a href="/posts/:id/comments">Comments</a>
        </script>

        <script type="text/template" id="postFormTemplate">
            <form>
                <input id="name" type="text"></input>
                <input id="title" type="text"></input>
                <textarea id="content"></textarea>
                <button id="postpost"></button>
            </form>
        </script>

        <!--Comment Templates-->

        <script type="text/template" id="commentsListTemplate">
            <a href="/">All Posts</a>
            <a href"/posts/:id">Post</a>

            <h1>Comments</h1>

            <ul></ul>
        </script>

        <script type="text/template" id="commentsListItemTemplate">
            <li>
                <p>{{name}}</p>
                <p>{{pubDate}}</p>
                <p>{{content}}</p>
            </li>
        </script>

        <script type="text/template" id="commentFormTemplate">
            <form>
                <input id="name" type="text"></input>
                <textarea id="content"></textarea>
                <button id="postcomment"></button>
            </form>
        </script>

    <!--Linked Files: Libs & Scripts-->

        <script src="jquery.min.js"></script>
        <script src="underscore-min.js"></script>
        <script src="backbone-min.js"></script>
        <script src="app.js"></script>


    </head>

    <body>

    <!--Entry Point Scripts-->
        <!--Router can be-->
        <script>
            $(document).ready(function(){
                var approuter = new appRouter();
                Backbone.history.start({pushState: true});
            });     
        </script>
    </body>
</html>

server.js

//Require Modules
var express = require('express');
var waterline = require('waterline');
var sailsMongo = require('sails-mongo');
var path = require('path');
var serveStatic = require('serve-static');
var bodyParser = require('body-parser')

//Create Objects of Required Modules
    //Probably Https server, db Conenction
var app = express();
var orm = new waterline();

//Configs, Middlewares for Created Objects of Modules.
    //Dir to serve static assets; css, js, index.
    //Body parser; json, urlencoded
    //Config-object for Waterline.
app.use( serveStatic( path.join(__dirname, 'public') ) );
app.use(bodyParser.json());

var ormConfig = {
    adapters: {
        mongodbAdapter: sailsMongo
    },
    connections: {
        mongodbConnection: {
            adapter: 'mongodbAdapter',
            host: 'localhost',
            database: 'Blog',
            //port:,
            //user:,
            //password:,
        }
    }
};

//Define Db Schemae, Models
    //Define Models
    //Load Defined Models into ORM
var postModel = waterline.Collection.extend({
  identity: 'posts',
  connection: 'mongodbConnection',

  attributes: {
      title: 'string',
      author: {type: 'string', required: true},
      body:   'string',
      comments: [{ body: 'string', date: 'date' }],
      date: { type: 'date', default: Date.now, required: true },
      hidden: 'boolean',
      meta: {
        votes: 'integer',
        favs:  'integer'
      }
  }
});
orm.loadCollection(postModel);

//Init Created and Configured Objects of Modules
    //Init ORM. Init express server.
orm.initialize(ormConfig, function(err, models) {
    if(err) throw err;

    //! NOT MUST CODE. JUST TO ABBREVIATE
    app.models = models.collections;
    app.connections = models.connections;
});

app.listen(3333);

//Define Routes
app.get('/', function(req, res){
    res.render('index.ejs');
});

【问题讨论】:

  • 我已经意识到,在我的模板属性中,我没有通过创建template: _.template( $('#someTemplate').html() ) 来传递我通过 jQuery 选择的对象的 html。我做到了,现在我没有前两个错误。但是一个不同的,我知道为什么我没有定义它的服务器端路由,'/posts',服务器上集合的位置。问题解决了。但仍然无法理解为什么它会给出这样的错误消息,并且无法直接引导我。
  • 看起来你没有定义'posts'路由,所以jsut定义它并处理它
  • 是的。正如我在评论中所说,我现在知道了。但是为什么它给出了关于路由器的先前错误,而只有我缺少模板的 .html(),虽然它给出了下划线错误,但它似乎并不重要。

标签: node.js backbone.js express sails.js waterline


【解决方案1】:

下划线函数 _.template() 需要 html,因此,应该在 DOM 选择器 jQuery 选择的元素上使用 .html() 方法,以便在分配时获取所选对象的 html;

template1: _.template( $('#postsListTemplate') ),

如下;

template1: _.template( $('#postsListTemplate').html() ),.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-05
    • 2021-07-13
    • 2019-08-11
    相关资源
    最近更新 更多