Reputation: 15
From the Router, I create a Search View with the following code:
(The if
is to only create a new
View where one does not already exist, since the View never changes.)
search: function () {
if (!this.searchView) {
this.searchView = new SearchView();
}
$('#content').html(this.searchView.el);
this.headerView.selectMenuItem('search-menu');
},
In the View, I have an events hash, binding a click event to a search button:
events: {
"click .search-query": "search"
},
This results in the event only firing the first time the search button is used.
Removing the if
from the search function solves the problem.
This however does not seem to be the correct way to approach this, since the View should not need to be recreated (reinitialized and re-rendered).
I attempted to add this.delegateEvents();
to the render function of the Search View as follows (while leaving the if
in the search function), but it did not solve the problem:
render:function () {
console.log('rendering search...');
$(this.el).html(this.template());
this.delegateEvents();
return this;
},
Any suggestions would be appreciated.
Upvotes: 0
Views: 1440
Reputation: 10648
Since you're not calling render()
again, delegateEvents
won't be called again. You can just call delegateEvents
directly in your router. This is just an example; there are probably more elegant ways to do it.
delegateEvents
basically rebinds the events to your view. This is useful if the html of your views gets removed from the dom. That looks like what is happening in your example.
search: function () {
if (!this.searchView) {
this.searchView = new SearchView();
}
$('#content').html(this.searchView.el);
this.searchView.delegateEvents();
this.headerView.selectMenuItem('search-menu');
}
Upvotes: 1