backbonejs模板没有渲染,node.js

时间:2013-10-28 22:44:17

标签: javascript node.js backbone.js express

我一直在尝试通过nodecellar学习backbonejs,我已深入研究它并且很好地理解了数据传递的原理。

我有点卡住了,我正在拉掉一些Nodecellar代码并对其进行修改以掌握我对backbone.js的理解。我在渲染列表时遇到问题:

以下是代码:

Server.js

var express = require('express'),
path = require('path'),
http = require('http'),
wine = require('./routes/wines');
users = require('./routes/users');
impulse = require('./routes/impulse');
//dashboard = require('./routes/dashboard');

var app = express();


app.configure(function () {
    app.set('port', process.env.PORT || 3000);
    app.use(express.logger('dev'));  /* 'default', 'short', 'tiny', 'dev' */
    app.use(express.bodyParser()),
    app.use(express.static(path.join(__dirname, 'public')));
});

//impulse management dynamic display
app.get('/', impulse.findAll);
app.get('/impulse', impulse.findAll);


http.createServer(app).listen(app.get('port'), function () {
    console.log("Express server listening on port " + app.get('port'));
});

所以,我们可以看到服务器是在端口3000上设置的。模型看起来像这样,它有一些验证:

模型。

window.Impulse = Backbone.Model.extend({

    urlRoot: "/impulse",

    idAttribute: "_id",

    initialize: function () {
        this.validators = {};

        this.validators.page = function (value) {
            return value.length > 0 ? {isValid: true} : {isValid: false, message: "The module needs a url"};
        };

        this.validators.picture = function (value) {
            return value.length > 0 ? {isValid: true} : {isValid: false, message: "The module needs a unique picture"};
        };

        this.validators.description = function (value) {
            return value.length > 0 ? {isValid: true} : {isValid: false, message: "The module needs a description"};
        };
    },

    validateItem: function (key) {
        return (this.validators[key]) ? this.validators[key](this.get(key)) : {isValid: true};
    },

    // TODO: Implement Backbone's standard validate() method instead.
    validateAll: function () {

        var messages = {};

        for (var key in this.validators) {
            if(this.validators.hasOwnProperty(key)) {
                var check = this.validators[key](this.get(key));
                if (check.isValid === false) {
                    messages[key] = check.message;
                }
            }
        }

        return _.size(messages) > 0 ? {isValid: false, messages: messages} : {isValid: true};
    },

    defaults: {
        _id: null,
        page: "#",
        picture: "users.png",
        name: "Impulse Dynamic Engine",
        subicon: "fa-exclamation-triangle",
        description: "The Impulse view engine has not been set up correctly or has failed to set up. Please contact SandWTech for technical support."
    }
});

window.ImpulseCollection  = Backbone.Collection.extend({

    model: Impulse,

    url: "/impulse"

});

Routes.js 根据app.get功能处理路由,因此我目前只拥有app.js中调用的内容。

var mongo = require('mongodb');

var Server = mongo.Server,
    Db = mongo.Db,
    BSON = mongo.BSONPure;

var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('engine', server, {safe: true});

db.open(function(err, db) {
    if(!err) {
        console.log("Connected to the engine database");
        db.collection('impulse', {safe:true}, function(err, collection) {
            if (err) {
                console.log("WARNING 'impulse' collection doesn't exist. Setting up impulse settings");
                populateDB();
            }
        });
    }
});


exports.findAll = function(req, res) {
    db.collection('impulse', function(err, collection) {
        collection.find().toArray(function(err, items) {
            res.send(items);
        });
    });
};

Main.js 处理路线并决定要显示的内容。

var AppRouter = Backbone.Router.extend({

routes: {
    ""                  : "home",
    "impulse"           : "home",
    "*actions"          : "home"
},


initialize: function () {
        this.headerView = new HeaderView();
        $('.header').html(this.headerView.el);
    },

    home: function (page) {
      var p = page ? parseInt(page, 10) : 1;
        var impulseList = new ImpulseCollection();
        impulseList.fetch({success: function(){
            $("#content").html(new HomeView({model: impulseList, page: p}).el);
        }});
        this.headerView.selectMenuItem('home-menu');
    },
utils.loadTemplate(['HomeView', 'HeaderView', 'WineView', 'WineListItemView', 'AboutView'], function() {
    app = new AppRouter();
    Backbone.history.start();
});

该模型应该传递到 HomeView 并显示:

<a href="#impulse/<%= page %>" class="thumbnail plain" style="text-align: center;">
    <img src="<%= picture === null ? 'pics/generic.jpg' : 'pics/' + picture %>" height="150" width="125" alt="">
    <h5><%= name %></h5>
    <br/>
    <i class="<%= subicon %>"></i> <%= description %>
</a>

现在,当我去运行时,我收到以下错误:

  

未捕获TypeError:对象[object Object]没有方法'template'

错误发生在home.js的第35行,其中包含homeView:

window.HomeView = Backbone.View.extend({

initialize: function () {
    this.render();
},

render: function () {
    var impulses = this.model.models;
    var len = impulses.length;
    var startPos = (this.options.page - 1) * 8;
    var endPos = Math.min(startPos + 8, len);

    $(this.el).html('<ul class="thumbnails"></ul>');

    for (var i = startPos; i < endPos; i++) {
        $('.thumbnails', this.el).append(new HomeViewItemView({model: impulses[i]}).render().el);
    }

    $(this.el).append(new Paginator({model: this.model, page: this.options.page}).render().el);

    return this;
    }
});

window.HomeViewItemView = Backbone.View.extend({

    tagName: "li",

    initialize: function () {
        this.model.bind("change", this.render, this);
        this.model.bind("destroy", this.close, this);
    },

    render: function () {
        $(this.el).html(this.template(this.model.toJSON()));
        return this;
    }

});

它说错误在这里:

   $(this.el).html(this.template(this.model.toJSON()));

但我不能因为我的生活而坚定不移。

为什么模板在正确连接时无法呈现?我错过了什么? GAAAAAAAHHHHHH !!!!

1 个答案:

答案 0 :(得分:1)

在HomeView中,您有以下代码:

new HomeViewItemView({model: impulses[i]})

而且在HomeViewItemView中你有:

$(this.el).html(this.template(this.model.toJSON()));

但我在HomeViewItemView中没有看到模板。这是未定义的。