我有一个measure
模型,它由两个集合组成,一个beats
集合和一个measureRep
[resentation]集合。每个集合分别由beat
个模型和representation
模型组成。
每当measureRep
[resentation]集合发生变化时(通过representation
模型的加法或减法),我想要measureView
(具有measure
模型,并且因此measureRep
[resentation]集合)使用渲染函数()重新渲染自己。
我将通过以下函数在另一个视图中添加新模型:
var representationModel = new RepresentationModel({representationType: newRepType});
StageCollection.get(cid).get('measures').models[0].get('measureRepresentations').add(representationModel);
我可以看到,在添加之前和之后,measure
及其measureRep
集合正在被正确添加,但measureView
上的绑定调用未注册更改,调用渲染功能。我甚至将绑定放在模型上,以显示后端正在更新,但是,它没有响应。这让我相信View和模型是分离的,但这没有意义,因为它最初是从模型渲染的。以下是相关文件:
measureView.js [查看]:
define([...], function(...){
return Backbone.View.extend({
initialize: function(options){
if (options) {
for (var key in options) {
this[key] = options[key];
}
this.el = '#measure-container-'+options.parent.cid;
}
window.css = this.collectionOfRepresentations; //I use these to attach it to the window to verify that the are getting updated correctly
window.csd = this.model; // Same
_.bindAll(this, 'render'); // I have optionally included this and it hasn't helped
this.collectionOfRepresentations.bind('change', _.bind(this.render, this));
this.render();
},
render: function(){
// Make a template for the measure and append the MeasureTemplate
var measureTemplateParameters = { ... };
var compiledMeasureTemplate = _.template( MeasureTemplate, measureTemplateParameters );
// If we are adding a rep, clear the current reps, then add the template
$(this.el).html('');
$(this.el).append( compiledMeasureTemplate )
// for each rep in the measuresCollection
_.each(this.collectionOfRepresentations.models, function(rep, repIndex) {
var measureRepViewParamaters = { ... };
new MeasureRepView(measureRepViewParamaters);
}, this);
return this;
},
...
});
});
measure.js [型号]:
define([ ... ], function(_, Backbone, BeatsCollection, RepresentationsCollection) {
var MeasureModel = Backbone.Model.extend({
defaults: {
beats: BeatsCollection,
measureRepresentations: RepresentationsCollection
},
initialize: function(){
var logg = function() { console.log('changed'); };
this.measureRepresentations.bind('change', logg);
this.bind('change', logg);
}
});
return MeasureModel;
});
representations.js [收藏]:
define([ ... ], function($, _, Backbone, RepresentationModel){
var RepresentationsCollection = Backbone.Collection.extend({
model: RepresentationModel,
initialize: function(){
}
});
return RepresentationsCollection;
});
我也尝试在measure
模型上注册绑定,而不是它的子集合,但都没有工作。
_.bindAll(this, 'render');
this.model.bind('change', _.bind(this.render, this));
答案 0 :(得分:1)
请参阅:https://stackoverflow.com/a/8175141/1449799
为了检测集合中模型的添加,您需要侦听add事件(而不是更改事件,当集合中的模型发生更改时将触发更改事件http://documentcloud.github.io/backbone/#Events-catalog)。
所以试试:
this.measureRepresentations.bind('add', logg);