Xrender
Xrender

Reputation: 1445

multiple instances of a view

I have a backbone view - which when called presents a form

$('#add-offer').click(function() {
    console.log("Here");
    formView = new TB_BB.RequestFormView({model : new TB_BB.Request(), el : '#main-container'});
    formView.render();
});

The view looks like

TB_BB.RequestFormView = Backbone.View.extend({
    initialize : function(){
        this.template = $("#formTemplate"); 
        _.bindAll(this,"render");
    },
    events : {
        "submit #request-form" : "save",
    },
    render : function() {       
        $('#add-offer-button').hide();
        $(self.el).show();      
        var content = this.template.tmpl();
        $(this.el).html(content);
        return this;
    },
    save : function(event){
        console.log("Saved ");      
        event.preventDefault();
    }
});

I have found that every time the submit #request-form

Event is triggered, it is triggered to EVERY instance of that view - however I thought it would be out of scope.

So for example if I on documentload call

$(function(){
    //create the router...  
    TB_BB.r = new TB_BB.Requests(TB_BB.initialData.requests);
    app = new TB_BB.Router();   
    Backbone.history.start();
    formView2 = new TB_BB.RequestFormView({model : new TB_BB.Request(), el : '#main-container'});
    formView3 = new TB_BB.RequestFormView({model : new TB_BB.Request(), el : '#main-container'});
    formView2.render();
});

And then I click the submit of the form, I see 'Saved' 3 times in the console rather than one? should that happen? can I only have one instance of a view?

Any help appreciated

Upvotes: 3

Views: 4352

Answers (1)

Sander
Sander

Reputation: 13421

you can have multiple instances of a view, and they will be of a separate scope as long as they are working with different dom elements.

you, on the other hand, pass the dom element to the view, via the el argument, so you specifically tell your 2 or 3 views that they need to manage the same element. thus they will both trigger on your submit button.

$(function(){
    //create the router...  
    ...

    // here you pass #main-container as the element for the view, 
    // so both these two views, will be handeling the same element. 
    // So, if some event is triggered within that scope, like a click on 
    // a submit button inside this scope, both the views will get the event triggered.
    formView2 = new TB_BB.RequestFormView({model : new TB_BB.Request(), el : '#main-container' });
    formView3 = new TB_BB.RequestFormView({model : new TB_BB.Request(), el : '#main-container' });

    ...
});

you can have multiple instances of a view, working separately, you can see examples of that, on the backbone documentation's example section

one of the best known examples would be the TODO application (source) where all todo items are instances of the same todoView, each managing click events within their own scope.

Upvotes: 4

Related Questions