我的骨干应用程序中有一些通过API查询数据库的搜索功能,但由于某种原因它会触发4次(或至少返回结果4次)。
这是我的代码,
集合
App.Collections.SearchableCollection = Backbone.Collection.extend({},{
search: function(query, options) {
var search = $.Deferred();
options = options || {};
var collection = new this([], options);
collection.url = _.result(collection, 'url');
var fetch = collection.fetch({
data: {
q: query
}
});
fetch.done(_.bind(function(){
Pops.EVENTS.trigger('search:done');
search.resolveWith(this, [collection]);
}, this));
fetch.fail(function(){
Pops.EVENTS.trigger('search:fail');
search.reject();
});
return search.promise();
}
});
App.Collections.ProjectSearch = App.Collections.SearchableCollection.extend({
url: Pops.API_ROOT + '/search/projects',
});
视图
App.Views.GlobalResults = Backbone.View.extend({
el : '.ui-grid-list--results',
events: {
"click .js-open-project" : "removeSearchView"
},
initialize: function() {
this.addAll();
},
render: function() {
var noResult = new Pops.Views.NoGlobalResult;
this.$el.before(noResult.render().el);
return this;
},
addAll: function() {
if(this.collection.length > 0) {
this.collection.each(this.addOne, this);
} else {
this.render();
}
},
addOne: function(model) {
var resultItem = new Pops.Views.GlobalResult({
model:model
});
this.$el.append( resultItem.render().el );
},
removeSearchView: function(e) {
setTimeout(function(){
$('.ui-fullscreen').remove();
}, 1000);
}
});
App.Views.NoGlobalResult = Backbone.View.extend({
className: 'ui-message-block',
template: _.template("<h5>No Results Found</h5><p>Sorry, we could not find any projects that matched your serach criteria.</p>"),
initialize: function() {
},
render: function() {
this.$el.html( this.template() );
return this;
}
});
App.Views.GlobalResult = Backbone.View.extend({
tagName : 'li',
className: 'ui-grid-list__item',
template: _.template( $('#tpl-project-list-item').html() ),
initialize: function() {
},
render: function() {
var self = this;
var pjCreatedDate = moment( this.model.get('created_at'), 'YYYY-MM-DD HH:mm:ss' ) ;
var userCreatedDate = moment( Pops.Session.get('created_at'), 'YYYY-MM-DD HH:mm:ss' ) ;
var oneWeekBeforeuserCreatedDate = userCreatedDate.subtract(8, 'day') ;
var giveNewTag = pjCreatedDate.isAfter(oneWeekBeforeuserCreatedDate) && (typeof this.model.get('projectview') != 'undefined' && this.model.get('projectview').length === 0);
if(this.model.get('project_manager') instanceof Backbone.Collection === false){
this.model.set({'project_manager':new App.Collections.Users},{silent:true});
}if(this.model.get('collaborators') instanceof Backbone.Collection === false){
this.model.set({'collaborators':new App.Collections.Users},{silent:true});
}if(this.model.get('organisations') instanceof Backbone.Model === false){
var organisations = this.model.get('organisations');
this.model.set({'organisations':new Pops.Models.Organisation(organisations)},{silent:true});
}if(this.model.get('user') instanceof Backbone.Model === false){
var users = this.model.get('user');
this.model.set({'user':new Pops.Models.User(users)},{silent:true});
}if(this.model.get('clients') instanceof Backbone.Model === false){
var clients = this.model.get('clients');
this.model.set({'clients':new Pops.Models.Client(clients)},{silent:true});
}
var projectmanagers = this.model.get('project_manager').toJSON();
var collaborators = this.model.get('collaborators').toJSON();
var collabs = projectmanagers.concat(collaborators);
this.$el.html( this.template({
project: this.model.toJSON(),
newTag: giveNewTag,
collaborators: collabs
}));
this.model.get('project_manager').each(function(model, i){
if(i < 3) {
var newUser = new Pops.Views.UserInitials({
model:model
});
self.$('.ui-inline-list').append(newUser.render().el);
}
});
this.model.get('collaborators').each(function(model, i){
if(i < 3) {
var newUser = new Pops.Views.UserInitials({
model:model
});
self.$('.ui-inline-list').append(newUser.render().el);
}
});
var numPeople = this.model.get('collaborators').models.length + this.model.get('project_manager').models.length - 6;
console.log(numPeople);
if(numPeople > 0) {
self.$('.ui-inline-list').append('<li class="ui-inline-list__item"> + ' + numPeople + ' more</li>');
}
this.$el.attr('data-id', this.model.get('id'));
this.$el.attr('data-organisationid', this.model.get('organisation_id'));
if(this.model.get('archived_at') !== null) {
this.$el.addClass('ui-list-block__item--archived');
this.$el.addClass('ui-list-block__item--archived-' + parseInt(moment(this.model.get('archived_at'), 'YYYY-MM-DD HH:mm:ss').format('YYYY'), 10));
}
if( this.model.get('visible') == false ) {
this.$el.hide();
}
if($('.ul-projects a[data-objectid="'+this.model.id+'"]').length < 1 ){
this.$el.addClass('ui-list-block__item--closed');
}
return this;
}
在此视图中触发搜索
App.Views.GlobalSearch = Backbone.View.extend({
el : 'body',
template: _.template($('#tpl-global-search').html() ),
events: {
"click .js-close-fullscreen" : "removeView",
"click .js-make-filter" : "setSearchFilter",
"click .js-trigger-search" : "doSearch",
"keyup input[name=search]" : "processKey"
},
initialize: function() {
},
render: function() {
this.$el.append(this.template());
return this;
},
removeView: function(e) {
e.preventDefault();
this.$('.ui-fullscreen').remove();
},
setSearchFilter: function(e) {
e.preventDefault();
var element = $(e.currentTarget);
var selectedText = element.text();
this.collectionName = element.data('collection');
this.isArchived = element.data('archived');
this.$('.dropdown-toggle').find('span:first').text(selectedText);
},
processKey: function(e) {
if(e.which === 13){
this.$('.js-trigger-search').trigger("click");
}
},
doSearch: function(e) {
e.preventDefault();
var self = this;
this.$('.global-search-container').removeClass('error').find('p').remove()
if(this.collectionName == undefined) {
this.collectionName = "ProjectSearch";
this.isArchived = "all";
}
this.$('.js-trigger-search').find('i').removeClass('fa-search').addClass('fa-refresh spin')
this.$('.ui-grid-list--results').empty();
this.$('.ui-message-block').remove();
var projects = App.Collections[this.collectionName];
var findProjects = projects.search({ string: this.$('[name=search]').val(), archived: this.isArchived });
findProjects.done(function(projects){
//console.log(projects)
var resultsView = new App.Views.GlobalResults({
collection: projects
});
//resultsView.render();
self.$('.js-trigger-search').find('i').removeClass('fa-refresh spin').addClass('fa-search')
});
}
});
现在我从来没有使用$ .deferred或promise's,所以可能是我使用它们错了,但我不认为是这样的。
搜索只需使用
进行初始化 var searchResults = new App.Views.GlobalResults;