2
votes

I am a newbie to backbone and trying to start using in our projects.

My requirement is I have something like this

var TextFields = Backbone.Model.extend({});

var TextFieldsCollection = Backbone.Collection.extend({});

var Module = Backbone.Model.extend({

    defaults: {
        fields: new TextFieldsCollection()
});

var ModuleCollection = Backbone.Collection.extend({

    model: CTModule
});

Now I have views defined for TextFields & Modules. If I change a value in TextFields a event gets fired for the model and I am changing the value in the model but the collection is not getting updated. I tried to trigger backbone events in the child model but at the collection view I am not able to map to the correct model that triggered the change event.

Any comments are helpful. I am not in a position to use more libraries. Can this be done in Backbone?

1
It is bit confusing can you add your setters to the question. - StateLess
When you say "the collection is not getting updated" do you mean the collection view? - Michael.Lumley

1 Answers

0
votes

I do not know what is full code, but if you do it in a fashion that Backbone apps are usually written everything should work.

Quick tutorial:

var TestModel = Backbone.Model.extend({});
var TestModelCollection = Backbone.Collection.extend({ model: TestModel });

// now if you have a view for collection
var TestModelCollectionView = Backbone.View.extend({
  initialize: function(opts) {
    this.collection = opts.collection;
    this.collection.on('change', this.render, this) // so - rerender the whole view 
  }
});

//execution:    
var modelData = { foo: 'bar' };
var collection = new TestModelCollection([modelData]);

var view = new TestModelCollectionView({collection: collection});
view.render();

collection.first().set('your_attr', 'new_value'); // will cause rerender of view

//////

One more thing - if you have collection, which is kept by the model (in your case Modules model, which have collection as one of its attributes), and your view keeps that model, you will have to either bind directly from view to collection via model (this.model.get('fields').on( .... )), or rethrow collection event in your model

I hope I helped at least a bit.

//////

There might be some syntax errors in my code - didn't run it on js fiddle.