我正在圈子里跑来跑去,似乎在我目前正在实施backbone.js的应用程序中遗漏了一些东西.问题是我有一个主AppView,它初始化页面的各种子视图(图形,信息表等).我的愿望是能够根据导航时传递的参数标志来更改页面的布局.
我遇到的情况是,子视图引用了在呈现模板后将存在的dom元素,在主AppView初始化过程中无法访问这些元素.所以主要的问题是如何确保每个事件绑定过程都有适当的dom元素才能正确设置?
如果我在LayoutView中有一个绑定到模型更改的事件,则使用以下代码,将呈现布局,但后续视图无法正确呈现.我摆弄的一些东西是将所有视图'.el'值设置为html结构中的静态元素.这会使渲染发生,尽管这似乎脱离了利用'.el'提供的良好作用域能力.
示例代码:
//Wrapped in jquery.ready() function...
//View Code
GraphView = Backbone.View.extend({ // init, model bind, template, supporting functions});
TableView = Backbone.View.extend({ // init, model bind, template, supporting functions});
LayoutView = Backbone.view.extend({
initialize: function() {
this.model.bind('change:version', this.render, this);
},
templateA = _.template($('#main-template').html()),
templateB = _.template($('#secondary-template').html()),
render: function() {
if ('main' == this.model.get('version')) {
this.el.html(this.templateA());
} else {
this.el.html(this.templateB());
}
},
});
MainView = Backbone.View.extend({
initialize: function() {
this.layoutView = new LayoutView({
el: $('#layoutContainer'),
model: layout,
});
this.graphView = new …Run Code Online (Sandbox Code Playgroud) 我现在一直在乱用骨干几天,然后出现我认为骨干最终在模型中设置属性的顺序存在误解.我有以下代码:
在model.js文件中 -
SampleModel: Backbone.Model.extend({
urlRoot: 'a url',
defaults: {
attrA: 'value',
},
initialize: function() {
// init of model relationships
},
parse: function(response) {
this.set({attrA: response.attrAUpdateValue});
},
});
Run Code Online (Sandbox Code Playgroud)
在view.js文件中 -
SampleView = Backbone.View.extend({
initialize: function() {
model = new SampleModel();
model.fetch();
console.log(model.get('attrA')); // Returns 'value' from default.
console.log(model.attributes); // Inspect the attributes for the model and see that attrA does not have updated value.
},
});
Run Code Online (Sandbox Code Playgroud)
为了使用attrA,我如何确保在更改模型之外的视图中工作时'attrA'是否有值?或者,这是在骨干领域中考虑它的方式吗?属性发生变化后,对模型执行某些操作?
在此先感谢您的帮助.
更新:我的错误我已经相应地更新了注释,之前我说第一个控制台日志将包含一个未定义的值.它应该声明该值是默认值的值,而不是应该在解析操作期间设置的预期更新值.