I’am searching for a way to filter my backbone collection with the value from a input field – to achieve this, I defined an event listener with the view (“keyup input.searchBookmark”: “search”):
window.BookmarksListView = Backbone.View.extend({
events: {
"keyup input.searchBookmark": "search"
},
el: $('#bookmarksList'),
initialize: function() {
this.model.bind("reset", this.render, this);
this.model.bind("add", function(bookmark) {
$('#bookmarksList').append(new BookmarksListItemView({model: bookmark}).render().el)
});
},
render: function(eventName) {
_.each(this.model.models, function(Bookmarks) {
$(this.el).append(new BookmarksListItemView({model: Bookmarks}).render().el);
}, this);
return this;
},
renderList: function(bookmarks) {
alert(bookmarks);
},
search: function(event) {
alert(event);
var query = $("#searchBookmark").val();
this.renderList(this.model.search(query));
}
});
The HTML:
<form class="pull-left" action="">
<input placeholder="Bookmarks..." type="text" class="searchBookmark" id="searchBookmark" value="">
</form>
The input element is not within the element “bookmarksList”.
My problem is that nothing happens if I enter some text into the input – what could be the problem?
When you use an
eventsobject in a Backbone view, they are bound using jQuery’sdelegate:So only elements that are within the view’s
this.elwill be bound using the view’sevents. You say thatso nothing gets bound to
input.searchBookmarkand yoursearchmethod never gets called.You have a few options:
#bookmarksListso that the list is self-contained.#bookmarksListto display and update the display when the collection changes. Then the view with the search box can filter the main bookmark collection, update the collection that#bookmarksListuses, and let Backbone’s event handling take it from there.input.searchBookmarkwhen your#bookmarksListview is rendered and unbind in itsremovemethod.The first two are pretty standard Backbone setups so there’s not much more to say about them; the third is a bit odd and would look something like this:
I don’t recommend this approach though, your views should keep their hands to themselves.