我正在尝试在我的主干集合上实现backgrid分页。它工作得很好,直到我实现过滤器。过滤集合后,分页器的页码发生了变化,但当我单击另一个页面时,什么都没有发生。这是我的模型和集合与过滤器功能:
var Project = Backbone.Model.extend({});
var ProjectCollection = Backbone.PageableCollection.extend({
model: Project,
state: {pageSize: 2},
mode: "client",
queryParams: {
currentPage: "current_page",
pageSize: "page_size"
},
filterBy: function(filterBy,projectName) {
var filteredProj = this.fullCollection.filter(function(model) {
if(model.get(filterBy).indexOf(projectName) !== -1) {
return true;
}
return false;
});
return new ProjectCollection(filteredProj);
},
sortBy: function(sortingKey) {
this.setSorting(sortingKey);
this.fullCollection.sort();
},
});
这是我的分页视图:
var PaginationView = Backbone.View.extend({
tagName:"div",
el:".backgrid-paginator",
initialize: function(){
_.bindAll(this,'render','filterRender');
this.collection.on("reset",this.render);
this.collection.on("filter-by-project", this.filterRender);
},
filterRender: function (filterBy,projectName) {
if (!projectName) this.render;
var filteredProj = this.collection.filterBy(filterBy,projectName);
var filteredPaginator = new Backgrid.Extension.Paginator({
collection: filteredProj
});
this.$el.html("");
this.$el.append(filteredPaginator.render().el);
return this;
},
render: function(){
var paginator = new Backgrid.Extension.Paginator({
collection: this.collection
});
this.$el.html("");
this.$el.append(paginator.render().el);
return this;
}
});
这是我的表格的HTML:
<div class="form-group col-md-4 pull-right">
<input type="text" id="filter" name="filter" class="form-control" placeholder="Filter Projects">
</div>
<div class="col-md-12 margin-top" id="responsive-table">
<table class="table table-responsive" >
<thead>
<th id="sortBy-name">Projects</th>
<th id="sortBy-sector">Sector</th>
<th id="sortBy-status">Status</th>
<th id="sortBy-org">Funding Organisation</th>
<th id="sortBy-location">Location</th>
<th id="sortBy-budget">Budget</th>
</thead>
<tbody id="projects-list">
</tbody>
</table>
<div class="backgrid-paginator"></div>
</div>
这是我的模板
<script type="text/template" id="project-row-template">
<td><a href="/frontend/activity/details/<%= id %>"><%= name %></a></td>
<td><%= sector %></td>
<td><%= status %></td>
<td><%= fundingOrganisation %></td>
<td><%= location %></td>
<td><%= budget %></td>
</script>
我做错了什么?我似乎到处都找不到答案。我还应该提到,我是新的骨干js。请帮我一下。谢谢。
终于想出了解决办法。我还不知道问题的根源,但我是这样解决的:
- 先触发
resetCollection
函数 - 有
filterBy
函数返回this
因此,在我的代码中,resetCollection函数将类似于前面的filterBy函数。
resetCollection: function(filterBy,projectName) {
var filteredProj = this.fullCollection.filter(function(model) {
if(model.get(filterBy).indexOf(projectName) !== -1) {
return true;
}
return false;
});
this.fullCollection.reset(filteredProj); // Only change in previous filterBy function
},
我的filterBy方法就是
filterBy: function(filterBy,projectName) {
return this;
},
所以…这就是解决我的backgrid分页问题的方法。我认为之前的方法也应该有效。我认为这可能是一个错误与后网或主干....或者我的代码有问题:无论如何,希望这对面临类似问题的人有所帮助。