0

我已经开始通过 nodecellar 学习bonesjs,我已经深入研究了它,并且对数据如何传递的原理有很好的理解。

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

这是代码:

服务器.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>

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

未捕获的类型错误:对象 [对象对象] 没有方法“模板”

错误位于 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()));

但我终生无法摆脱它._.;

为什么模板全部正确连接后不渲染?我错过了什么?啊啊啊啊啊啊!!!!

4

1 回答 1

1

在 HomeView 中,您有以下代码:

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

与 HomeViewItemView 相比,您拥有:

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

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

于 2013-10-29T00:00:18.133 回答