I am creating a web application using backbone.js. I have two tabs. Tab 1 is a backbone.js view and tab2 is another backbone view (of the same kind).
Both the views are loaded to the same div element in the page. Currently what I do is, when user change the tab, I detect it using the backbone router. Then router does a check to see if a view is already there, or should it be created.
I created a object manager object, who store the view object based on a key (key is the tab name)
App.ObjectManager.getContentView = function (tabId) {
return App.ObjectManager.ContentHash[tabId];
};
App.ObjectManager.setContentView = function(tabId, view) {
App.ObjectManager.ContentHash[tabId] = view;
};
App.ObjectManager.hasContentView = function(tabId) {
if(App.ObjectManager.ContentHash[tabId]==undefined) {
return 0;
}
else{
return 1;
}
};
Here is what I do to create and store the view to list object. This code is called every time a tab is clicked, and router detects the change.
$("#myDiv").html("");
if(App.ObjectManager.hasContentView(tabId)==0) { //View is not in the lookup table
console.log("View is not created yet. So we need to create");
content = new App.MyBackboneView(); //create a new view
App.ObjectManager.setContentView(tabId, content); //Store the view
}
else {
console.log("View is already created..So we read it and show it");
content = App.ObjectManager.getContentView(tabId);
}
//Now, we add the view to the main div
$("#myDiv").append(content.el);
The code above works by showing the view to the myDiv. and I can see the values of text boxes and radio buttons, etc being shown.
The only thing – event handling don’t work. So, if I have a button in the view that is added an event handler, the event don’t get called when the view is rendered from the saved object. First time when the view gets shown, click event is handling.
For eg, I have this button in the view “Say My Name!”
events: {
"click #say": "sayName"
},
sayName: function() {
console.log("I click say Name");
}
First time the view gets loaded, when I press the button, console show me the log. When I come back to the tab again, and this time view is shown from the list object, the click event don’t work.
Is my code having any problem ?
Hope you can give me some way how to store the view and I can reuse the view again.
Thanks.
When creating a view you empty myDiv content
I think this action automatically removes all bindings that you set in your View earlier. It’s actually quite a common problem with Backbone – this framework sets event listeners to dom elements in the view.
Probably easiest way to deal with this issue is to create a parent View for #myDiv as a whole and set events in there.
View structure may look like that:
TabsView (set events here)
|
– Tab View 1 (render content)
– Tab View 2 (render content)