2013-11-20 49 views
1

我正在尝试学习骨干牵线木偶js并使用此框架开发小型应用程序。用户搜索动态过滤牵引木偶集合模型

作为应用程序的一部分,我显示复合集合视图中的用户列表,其中模式包含名称作为唯一属性。现在我想添加一个搜索按钮。当用户在搜索框中输入字符串时,我想要在关键字上动态地过滤名称。如果他清除了文本,我应该重置。

我试图寻找事件触发和聆听。但不能在我的情况下完全代码。

有人可以指导我如何听事件。 SearchBox不在此模板中。是否有可能从外部视听事件并执行过滤等操作。

下面是我的骨架模型和集合视图:

AttachmentModel = Backbone.Model.extend({ 
    defaults: { 
     name : "DefaultName" 
    } 
}); 

//collection definition 
AttachmentCollectionModel = Backbone.Collection.extend({ 
    model : AttachmentModel 
}); 

//View definition 
AttachmentView = Backbone.Marionette.ItemView.extend({ 
    template : "#attachment-item-template", 
    tagName : 'li' 
}); 

//Collection view definition 
AttachmentCollectionView = Backbone.Marionette.CompositeView.extend({ 
    tagName : "ul", 
    className : "list", 
    template : "#attachment-collection-template", 
    itemView : AttachmentView 
}); 

//Adding region 
MyApp.addRegions({ 
    attachmentsDisplayContainer : "#attachmentsDisplayContainer" 
}); 

//Adding initializer 
MyApp.addInitializer(function(options){ 
    var attachmentCollectionView = new AttachmentCollectionView({ 
     collection : options.attachmentCollectionModels 
    }); 
    MyApp.attachmentsDisplayContainer.show(attachmentCollectionView);  
}); 

回答

1

我有木偶没有经验,但在你的情况下,我将创建一个搜索查看,将控制搜索事件。该SearchView将持有对AttachmentCollectionView的引用,并且对于每个keyEvent都会调用方法search(name)或类似方法。我认为在视图模板之外绑定事件不是一个好主意。

//SearchView 

SearchView = Backbone.View.extend({ 
    events: { 
     "onkeyup .searchField: filterResult" 
    }, 
    initialize: function(options){ 
     this.attachmentCollectionView = options.attachmentCollectionView; 
    }, 
    filterResult: function(e) { 
     this.attachmentCollectionView.searchResult(); 
    } 
}); 

AttachmentCollectionView = Backbone.Marionette.CompositeView.extend({ 
    tagName : "ul", 
    className : "list", 
    template : "#attachment-collection-template", 
    itemView : AttachmentView, 

    searchResult: function(name){ 
     //Filter your list view and update your view 
    } 
}); 

//Adding initializer 
MyApp.addInitializer(function(options){ 
    var attachmentCollectionView = new AttachmentCollectionView({ 
     collection : options.attachmentCollectionModels 
    }); 
    var searchView = new SearchView({ 
     attachmentCollectionView = attachmentCollectionView 
    }); 

    MyApp.attachmentsDisplayContainer.show(attachmentCollectionView);  

    searchView.render(); 
}); 
+0

我应该在哪里注册searchView?应用程序如何知道搜索视图。我应该在某个地方绑定对吗?它会在哪里? 你可以给更多的细节 – Rajeev

+0

我已经扩展了代码。正如我之前说过的,我没有使用Marionette的经验,但是对于searchView,您可以像创建任何其他视图一样创建它,例如在初始化程序中,然后在创建时将它传递给AttachmentCollectionView。 – Markinhos