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
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
elargument, 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.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.