[英]backbone.js - filtering a collection with the value from a input
我正在尋找一種使用輸入字段中的值來過濾我的主干集合的方法-為此,我定義了一個帶有視圖的事件監聽器(“ 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));
}
});
HTML:
<form class="pull-left" action="">
<input placeholder="Bookmarks..." type="text" class="searchBookmark" id="searchBookmark" value="">
</form>
輸入元素不在元素“ bookmarksList”內。
我的問題是如果我在輸入中輸入一些文本沒有任何反應 - 可能是什么問題?
當您在Backbone視圖中使用events
對象時, 它們將使用jQuery的delegate
進行綁定 :
delegateEvents
delegateEvents([events])
使用jQuery的
delegate
函數為視圖中的DOM事件提供聲明性回調。 如果未直接傳遞events
哈希,請使用this.events
作為源。
因此,只有視圖的this.el
的this.el
才會使用視圖的events
進行綁定。 你這么說
input元素不在元素“bookmarksList”中
因此,沒有內容綁定到input.searchBookmark
並且永遠不會調用您的search
方法。
你有幾個選擇:
#bookmarksList
以便列表是獨立的。 #bookmarksList
設置單獨的書簽集合,以在集合更改時顯示和更新顯示。 然后帶有搜索框的視圖可以過濾主要的書簽集合,更新#bookmarksList
使用的集合,並讓Backbone的事件處理從那里獲取它。 #bookmarksList
視圖時手動綁定到input.searchBookmark
,並在其remove
方法中解除綁定。 前兩個是非常標准的Backbone設置,因此無需多說。 第三個有點奇怪,看起來像這樣:
window.BookmarksListView = Backbone.View.extend({
events: { },
initialize: function() {
_.bindAll(this, 'search');
//...
},
render: function(eventName) {
$('input.searchBookmark').on('keyup', this.search);
//...
},
remove: function() {
$('input.searchBookmark').off('keyup', this.search);
// Other cleanup...
},
//...
});
我不推薦這種方法,你的意見應該自己動手。
我通過為輸入字段的視圖觸發消息來處理過濾:
class App.Views.SidebarListSearchView extends Backbone.View
el: "input#list-search"
events:
keyup: "filter"
# Send a message with the value we are searching for.
filter: => App.Mediator.trigger("filterLists", $(@el).attr("value"))
...其他觀點聽:
class App.Views.SidebarFolderView extends Backbone.View
...
initialize: ->
# Re-render the shebang with a filter applied.
App.Mediator.bind("filterLists", @filterLists)
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.