Javascript backbone.js-使用输入中的值筛选集合
我正在寻找一种方法,用输入字段中的值过滤我的主干集合-为此,我使用视图(“keyup input.searchBookmark”:“search”)定义了一个事件侦听器: HTML:Javascript backbone.js-使用输入中的值筛选集合,javascript,backbone.js,Javascript,Backbone.js,我正在寻找一种方法,用输入字段中的值过滤我的主干集合-为此,我使用视图(“keyup input.searchBookmark”:“search”)定义了一个事件侦听器: HTML: <form class="pull-left" action=""> <input placeholder="Bookmarks..." type="text" class="searchBookmark" id="searchBookmark" value=""> </for
<form class="pull-left" action="">
<input placeholder="Bookmarks..." type="text" class="searchBookmark" id="searchBookmark" value="">
</form>
输入元素不在元素“bookmarksList”内
我的问题是,如果我在输入中输入一些文本,则不会发生任何事情-可能有什么问题?当您在主干视图中使用
事件
对象时:
delegateventsdelegatevents([events])
使用jQuery的delegate
函数为视图中的DOM事件提供声明性回调。如果未直接传递events
哈希,则使用this.events
作为源
因此,只有视图的this.el中的元素才会使用视图的事件绑定。你这么说
输入元素不在元素“bookmarksList”内
因此,没有任何东西绑定到input.searchBookmark
,您的search
方法永远不会被调用
您有几个选择:
将搜索框移动到#bookmarksList
中,使列表自包含
将搜索事件处理移动到包含搜索框的视图。然后为#bookmarksList
设置单独的书签集合,以便在集合更改时显示和更新显示。然后,带有搜索框的视图可以过滤主书签集合,更新#bookmarksList
使用的集合,并让主干网的事件处理从此处开始
当呈现#bookmarksList
视图时,手动绑定到input.searchBookmark
,并在其remove
方法中解除绑定
前两个是相当标准的主干网设置,因此没有更多关于它们的说明;第三个有点奇怪,看起来像这样:
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)
...
class App.Views.SidebarFolderView extends Backbone.View
...
initialize: ->
# Re-render the shebang with a filter applied.
App.Mediator.bind("filterLists", @filterLists)
...