From 73404332e83a7bf7bb6f85d1099bae41d5f5e8e2 Mon Sep 17 00:00:00 2001 From: Timo Tijhof Date: Wed, 21 May 2014 03:07:08 +0200 Subject: [PATCH] mediawiki.searchSuggest: Code clean up * Cache mw.Api instance. * Remove redundant "str.length" check in fetch(), jquery.suggestions already takes care of this (it never calls fetch if the string is empty, and if it did, then this code would've left it unhandled causing bugs (e.g. suggestions of the previous fetch remain visible). * Remove redundant promise.abort check. * Use $.data() and $.removeData() to bypass unneeded convenience logic for collections and HTML data attributes. Change-Id: I59ae21c4b481ef52e4db14cb1f3f2fe026c23b3f --- .../src/mediawiki/mediawiki.searchSuggest.js | 43 ++++++++++--------- 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/resources/src/mediawiki/mediawiki.searchSuggest.js b/resources/src/mediawiki/mediawiki.searchSuggest.js index cbdf66600e..c2c70b00f2 100644 --- a/resources/src/mediawiki/mediawiki.searchSuggest.js +++ b/resources/src/mediawiki/mediawiki.searchSuggest.js @@ -3,7 +3,7 @@ */ ( function ( mw, $ ) { $( function () { - var map, resultRenderCache, searchboxesSelectors, + var api, map, resultRenderCache, searchboxesSelectors, // Region where the suggestions box will appear directly below // (using the same width). Can be a container element or the input // itself, depending on what suits best in the environment. @@ -121,33 +121,34 @@ $( searchboxesSelectors.join( ', ' ) ) .suggestions( { fetch: function ( query ) { - var $el; - - if ( query.length !== 0 ) { - $el = $( this ); - $el.data( 'request', ( new mw.Api() ).get( { - action: 'opensearch', - search: query, - namespace: 0, - suggest: '' - } ).done( function ( data ) { - $el.suggestions( 'suggestions', data[1] ); - } ) ); - } + var $textbox = this, + node = this[0]; + + api = api || new mw.Api(); + + $.data( node, 'request', api.get( { + action: 'opensearch', + search: query, + namespace: 0, + suggest: '' + } ).done( function ( data ) { + $textbox.suggestions( 'suggestions', data[1] ); + } ) ); }, cancel: function () { - var apiPromise = $( this ).data( 'request' ); - // If the delay setting has caused the fetch to have not even happened - // yet, the apiPromise object will have never been set. - if ( apiPromise && $.isFunction( apiPromise.abort ) ) { - apiPromise.abort(); - $( this ).removeData( 'request' ); + var node = this[0], + request = $.data( node, 'request' ); + + if ( request ) { + request.abort(); + $.removeData( node, 'request' ); } }, result: { render: renderFunction, select: function () { - return true; // allow the form to be submitted + // allow the form to be submitted + return true; } }, delay: 120, -- 2.20.1