簡體   English   中英

骨架.js-使用輸入中的值過濾集合

[英]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.elthis.el才會使用視圖的events進行綁定。 你這么說

input元素不在元素“bookmarksList”中

因此,沒有內容綁定到input.searchBookmark並且永遠不會調用您的search方法。

你有幾個選擇:

  1. 將搜索框移到#bookmarksList以便列表是獨立的。
  2. 將搜索事件處理移至包含搜索框的視圖。 然后為#bookmarksList設置單獨的書簽集合,以在集合更改時顯示和更新顯示。 然后帶有搜索框的視圖可以過濾主要的書簽集合,更新#bookmarksList使用的集合,並讓Backbone的事件處理從那里獲取它。
  3. 在呈現#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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM