0
votes

currently I'm fiddling around with Marionette and Backbone (because I have to). I have a list of entities: CompositeView with ItemViews, every ItemView has a model with data like firstname and lastname.

In each ItemView is a link that will catch new data for the ItemView via AJAX (another endpoint!) and should update the view with a list of additional data like: [{"id": 1, "foo": "this is soo bar"}, {"id": 2, "foo": "a little bit of baz"}]. That data should be rendered then into the view (and can be removed again on a click).

What's the best way to go here? Adding a second model within the ItemView or add the new data to the existing view? Or something completely different? I appreciate every helpful tip!

My Solution (kind of)

Here is what I ended up with: when the link for the additional data is clicked, the associated ItemView instanciates a Backbone.Collection object I defined. That collection holds the URL for the endpoint. Then, I call the collection.fetch() method and render that collection with Underscore like this (roughly):

var tpl = _.template(dataTemplate);
var html = tpl({ myData: {collection.models});

node.html(html);

Thank you guys for thinking with me :)

1
"every ItemView has a model with data like firstname and lastname" - Where does this data come from? an endpoint or something else? - T J
Exactly. The App will be initiated on a button click, will call an AJAX endpoint and will then render this (JSON) data first. Edit: but that endpoint is another one - Hando
basically you cannot have multiple models for one itemview - nikhil mehta
But I could add additional data to the existing one, right? The additional data won't be synchronized or something. So maybe I will just render the data from the second call... - Hando
@Hando for that I guess github.com/theironcook/Backbone.ModelBinder is a good option - nikhil mehta

1 Answers

0
votes

Bunch of different ways to solve, this is what I prefer

Template Helpers

var View = Mn.ItemView.extend({
    templateHelpers: function () {

        // Each property will be available in the template
        return {
            extraData: 'my data',
            anotherModel: this.getOption('secondModel').toJSON(),
            someOtherData: ''
        }
    }
});

new View({model: MyModel, secondModel: SecondModel});

To get extra data into the view from a parent, checkout childViewOptions

By the look of your data, its an array of items. So your childView for your CompositeView could be a CollectionView