1
votes

Say I've built a MainView (a list) that has populates a collection with four Backbone models. Then, for each model in the collection, I render a SubView (a list item) based off of the data in each model. Ignoring whether or not this nested view structure is optimal, how would I go about creating a click event on each subview (list item) that launches a new view referencing the model that was used to create it?

I roughed out what I'm trying to do (to some extent) in the following code:

var MainView = Backbone.View.extend({

initialize: function(){
            this.render();
    //fetch data into a collection
    this.collection.fetch().then(function(){
                this.subRender();
            });
    //view now has a list with four list items based on four models
},

events: {
    "click li": 'newView'
},

newView: function(){
    //retrieve the model from the clicked li
            //close the current view, then
    var newView = new NewView({model});
}

render: function(){
    //create an unordered list element
    this.$el.html('<ul id="list"></ul>');
},

subRender: function(){
    //for each model in the collection create a new subview
    var subView = new SubView({model: model}); // x 4 times

}

});

var SubView = Backbone.View.extend({

el: '#list',

render: function(){
    //create an <li> with the passed-in model
    //append it to the list
},
});

EDIT: There's a post at LosTechies that deals with this I finally found...

1

1 Answers

0
votes

I think you can just have a click event, but use stopImmediatePropagation();

var SubView = Backbone.View.extend({
    el: '#list',
    events: {
        "click": 'doHandler'
    },
    doHandler: function(event) {
        event.stopImmediatePropagation(); // need this to stop other click handlers and the event bubbling up to ancestor elements
        // do stuff 
    },
    render: function(){
        //create an <li> with the passed-in model
        //append it to the list
    },
});