我是backbone.js和handlebars的新手,在获取模板来呈现数据时遇到了问题。
以下是我从tagfeed.js模块收集的数据和模型数据:
// Create a new module.
var Tagfeed = app.module();
// Default model.
Tagfeed.Model = Backbone.Model.extend({
defaults : {
name : '',
image : ''
}
});
// Default collection.
Tagfeed.Collection = Backbone.Collection.extend({
model : Tagfeed.Model,
url : Api_get('api/call')
});
Tagfeed.TagView = Backbone.LayoutView.extend({
template: "tagfeed/feed",
initialize: function() {
this.model.bind("change", this.render, this);
},
render: function(template, context) {
return Handlebars.compile(template)(context);
}
});然后在我的路由器中,我有:
define([
// Application.
"app",
// Attach some modules
"modules/tagfeed"
],
function(app, Tagfeed) {
// Defining the application router, you can attach sub routers here.
var Router = Backbone.Router.extend({
routes: {
"index.html": "index"
},
index: function() {
var collection = new Tagfeed.Collection();
app.useLayout('main', {
views: {
".feed": new Tagfeed.TagView({
collection: collection,
model: Tagfeed.Model,
render: function(template, context) {
return Handlebars.compile(template)(context);
}
})
}
});
}
});
return Router;
});THis成功地调用了api,调用获取我的主模板,并调用获取提要模板。如果我不包括render( template,context)函数,那么它在页面上呈现为我在提要模板中直接显示HTML,但仍然包含{{ name }}。但是,当它包含在内时,我会得到错误
TypeError: this._input.match is not a function
[Break On This Error]
match = this._input.match(this.rules[rules[i]]);如果我检查传递给feed的appLayout视图呈现函数的变量,我看到template变量是一个函数,而context变量是未定义的,那么它就会抛出这个错误。
你知道我做错了什么吗?我知道我在这里至少有一个问题,可能更多。
发布于 2012-09-14 04:21:28
由于您正在使用requirejs,您可以使用text模块来外部化您的模板,或者更好地预编译它们并将它们包含在您的视图中。查看http://berzniz.com/post/24743062344/handling-handlebars-js-like-a-pro
例如使用预编译的模板
// router.js
define(['views/tag_feed', 'templates/feed'], function(TagFeedView) {
var AppRouter = Backbone.Router.extend({
// ...
});
})
// tag_feed.js
define(['collections/tag_feed'], function() {
return Backbone.View.extend({
// ...
render: function() {
this.$el.html(
Handlebars.templates.feed({
name: '...'
})
);
}
});
})作为参考,我为backbone/require/handlebars设置https://github.com/nec286/backbone-requirejs-handlebars创建了简单的样板
https://stackoverflow.com/questions/12410366
复制相似问题