我有一个measure模型,它由两个集合组成,一个是beats集合,另一个是measureRep资源集合。每个集合分别由beat模型和representation模型组成。
每当measureRep资源集更改时(通过添加或减去representation模型),我希望使用render函数()重新呈现measureView (它拥有measure模型,因此还有measureRep资源集合)。
我通过以下函数在另一个视图中添加了一个新模型:
var representationModel = new RepresentationModel({representationType: newRepType});
StageCollection.get(cid).get('measures').models[0].get('measureRepresentations').add(representationModel);我可以看到,在measure及其measureRep集合被正确添加之前和之后,measureView上的绑定调用没有注册更改并调用render函数。我甚至将绑定放在模型上,以表明后端正在更新,但是它没有响应。这使我相信,视图和模型是解耦的,但这是没有意义的,因为它最初是从模型中呈现的。以下是相关档案:
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));发布于 2013-08-23 16:03:25
请参阅:https://stackoverflow.com/a/8175141/1449799
为了检测模型添加到集合中的情况,您需要侦听添加事件(而不是变更事件,当集合中的模型更改http://documentcloud.github.io/backbone/#Events-catalog时,更改事件将触发)。
所以试着:
this.measureRepresentations.bind('add', logg);https://stackoverflow.com/questions/18363809
复制相似问题