【发布时间】:2013-10-21 22:07:22
【问题描述】:
我正在尝试掌握 Backbone.js,并一直遵循Thomas Davis 此处概述的“模块化”方法。
尝试在另一个视图中“包含”一个视图时,我似乎被卡住了,如下所示:
SettingsView.js
define([
'jquery',
'underscore',
'backbone',
'text!templates/settings/settingsTemplate.html'
], function($, _, Backbone, settingsTemplate){
var SettingsView = Backbone.View.extend({
el: $("#interface"),
render: function() {
this.$el.html(settingsTemplate);
}
});
return SettingsView;
});
ScriptView.js
define([
'jquery',
'underscore',
'backbone',
'views/settings/SettingsView',
'models/script/ScriptModel',
'collections/scripts/ScriptsCollection',
'text!templates/script/scriptTemplate.html'
],
function($, _, Backbone, SettingsView, ScriptModel, ScriptsCollection, scriptTemplate) {
var ScriptView = Backbone.View.extend({
el : $("#container"),
render : function() {
this.$el.html(scriptTemplate);
//add the settings view
var settingsView = new SettingsView();
settingsView.render();
}
});
return ScriptView;
});
更新:我已经设法修复了我刚刚意识到的错误,为什么会发生这种情况(参数顺序错误 - DOH!!)
我不再收到错误消息,但我的“SettingsView”仍未出现。当我在“ScriptView.js”中进行控制台记录时,我看到“el”是未定义的,所以我的想法是这可能是问题所在......?
谢谢
【问题讨论】:
-
作为一个服务器端js新手,恐怕帮不上什么忙,反正在scriptview.js中,'namespaces'中的名字顺序似乎与函数参数。 (可能是“没有方法”的原因)。似乎人们通常作为渲染的结果返回视图本身
-
另外(仍然是一个新手问题),这是什么.$el ?不应该是
this.el还是$(this.el)? -
谢谢 jbl - 是的,我刚刚意识到我自己因此更新了帖子;)。我现在已经让它工作了(我想?) - 至少我现在可以在页面上看到我的子视图,所以我猜它没关系。除了您提到的明显错误之外,我还将“SettingsView.js”中的渲染方法更改为: var compiledTemplate = _.template( settingsTemplate ); $("#interface").append(compiledTemplate); 这似乎成功了!