const getEntityFromChange = (sourceChange, changeValues) => { const mainEntry = { entity: { id: parseInt(decodeSliceValue(sourceChange.id), 10), entityType: { name: sourceChange.type } }, axes: changeValues.reduce((res, v) => { if (v.name && v.name.match(SLICE_CUSTOMFIELD_PREFIX)) { return res.concat({ type: 'customfield', customFieldName: v.name.replace(SLICE_CUSTOMFIELD_PREFIX, ''), targetValue: decodeSliceValue(v.value) }); } if (isStateRelated(v.name)) { return res.concat({ type: lc(v.name), targetValue: decodeSliceValue(v.value) }); } return res; }, []), replaceCustomFieldValueInChanges: noop }; return when(createRequirementsByTasks(mainEntry)) .then((reqs) => [mainEntry].concat(reqs)); };
function dataobjformat(resource, formatter) { if (!resource) return $.when(null); return resource.fetchIfNotPopulated().pipe(function() { formatter = formatter || resource.specifyModel.getFormat(); var formatterDef = formatter ? $(`format[name="${formatter}"]`, formatters) : $(`format[class="${resource.specifyModel.longName}"][default="true"]`, formatters); var sw = formatterDef.find('switch').first(); // external dataobjFormatters not supported if (!sw.length || sw.find('external').length) return null; // doesn't support switch fields that are in child objects var fields = (sw.attr('field') && (sw.attr('single') !== 'true') ? sw.find('fields[value="' + resource.get(sw.attr('field')) + '"]:first') : sw.find('fields:first')).find('field'); var deferreds = fields.map(function () { var fieldNode = $(this); var formatter = fieldNode.attr('formatter'); // hope it's not circular! var fieldName = fieldNode.text(); return resource.rget(fieldName).pipe(function(value) { return formatter ? dataobjformat(value, formatter) : fieldformat(resource.specifyModel.getField(fieldName), value); }); }); return whenAll(deferreds).pipe(function (fieldVals) { var result = []; fields.each(function (index) { if (!fieldVals[index]) return; var fieldNode = $(this); fieldNode.attr('sep') && result.push(fieldNode.attr('sep')); var format = fieldNode.attr('format'); if (!_(format).isUndefined() && format.trim() === '') return; result.push(fieldVals[index]); }); return result.join(''); }); }); }
reactivateUser() { const deferreds = [] for (let en of Array.from(this.model.get('enrollments'))) { const url = `/api/v1/courses/${ENV.course.id}/enrollments/${en.id}/reactivate` en.enrollment_state = 'active' deferreds.push($.ajaxJSON(url, 'PUT')) } return $('.roster-tab').disableWhileLoading( $.when(...Array.from(deferreds || [])) .done(() => { this.render() return $.flashMessage(I18n.t('User successfully re-activated')) }) .fail(() => $.flashError( I18n.t('Something went wrong re-activating the user. Please try again later.') ) ) ) }
Contents.prototype.restore_checkpoint = function(path, name, checkpoint_id, options) { var file_id_prm = gapi_utils.gapi_ready .then($.proxy(drive_utils.get_id_for_path, this, path + '/' + name, drive_utils.FileType.FILE)) var contents_prm = file_id_prm.then(function(file_id) { var request = gapi.client.drive.revisions.get({ 'fileId': file_id, 'revisionId': checkpoint_id }); return gapi_utils.execute(request); }) .then(function(response) { return gapi_utils.download(response['downloadUrl']); }) return $.when(file_id_prm, contents_prm) .then(function(file_id, contents) { console.log(contents); return drive_utils.upload_to_drive(contents, {}, file_id); }); };
function bootstrap () { return $.when( (function () { var member_url = '/node_modules/hk-legco-utils/data/member-json/all.json'; return $.getJSON(member_url).then(function (data) { return data; }); })(), (function () { var motions_url = '/node_modules/hk-legco-utils/data/voting-motion-json/1314/all.json'; return $.getJSON(motions_url).then(function (data) { data = _.filter(data, function (d) { return !d.ammendment && d.motion_en.toLowerCase().indexOf('amendment') < 0 && d.motion_en.toLowerCase().indexOf('amended') < 0; }); return data; }); })() ); }
.get(function (req, res){ var x; var tempDef = $.Deferred(); var result = {min: 0, max: 0, data: []}; var tempTopic = req.params.topic; var location = req.params.l; if (location == "USA"){ getTweetByTopicForUS(tempTopic, result, tempDef, location); } else { getTweetByTopic(tempTopic, result, tempDef, location); } $.when(tempDef).done(function(){ // Train the words for every call //trainWords(); res.json(result); }); });
self.activate = function () { self.view = 'countries'; self.user = globals.user; self.countries.removeAll(); self.regions.removeAll(); var c = ajax.get('countries'); var r = ajax.get('regions', { active: true }); return $.when(c, r).done(function (c, r) { ko.utils.arrayForEach(c[0], function (country) { self.countries.push(new CountryViewModel(country)); }); ko.utils.arrayForEach(r[0], function (region) { self.regions.push(region); }); }).fail(function (message) { app.showMessage(message, "Countries"); }); };
getTabContent: function() { var self = this, container = $('.tab-container'); $.when( $.getJSON('http://content.guardianapis.com/search?section=uk-news&page-size=10&api-key=9wur7sdh84azzazdt3ye54k4', function(data) { self._feeds['uk-news'] = data.response.results; }), $.getJSON('http://content.guardianapis.com/search?section=football&page-size=10&api-key=9wur7sdh84azzazdt3ye54k4', function(data) { self._feeds['football'] = data.response.results; }), $.getJSON('http://content.guardianapis.com/search?section=travel&page-size=10&api-key=9wur7sdh84azzazdt3ye54k4', function(data) { self._feeds['travel'] = data.response.results; }) ).then(function() { container.removeClass('loading'); self.populateFeedContent(container, self._sections, self._feeds); }); },
_showSeasons : function() { var self = this; this.seasons.show(new LoadingView()); this.seasonCollection = new SeasonCollection(this.model.get('seasons')); this.episodeCollection = new EpisodeCollection({ seriesId : this.model.id }).bindSignalR(); this.episodeFileCollection = new EpisodeFileCollection({ seriesId : this.model.id }).bindSignalR(); reqres.setHandler(reqres.Requests.GetEpisodeFileById, function(episodeFileId) { return self.episodeFileCollection.get(episodeFileId); }); reqres.setHandler(reqres.Requests.GetAlternateNameBySeasonNumber, function(seriesId, seasonNumber, sceneSeasonNumber) { if (self.model.get('id') !== seriesId) { return []; } if (sceneSeasonNumber === undefined) { sceneSeasonNumber = seasonNumber; } return _.where(self.model.get('alternateTitles'), function(alt) { return alt.sceneSeasonNumber === sceneSeasonNumber || alt.seasonNumber === seasonNumber; }); }); $.when(this.episodeCollection.fetch(), this.episodeFileCollection.fetch()).done(function() { var seasonCollectionView = new SeasonCollectionView({ collection : self.seasonCollection, episodeCollection : self.episodeCollection, series : self.model }); if (!self.isClosed) { self.seasons.show(seasonCollectionView); } }); },
module.exports = function (popListeMarkiert) { var markiertePop // falls noch aus dem Verorten ein Klick-Handler besteht: deaktivieren if (window.apf.olMap.LetzterKlickHandler) { window.apf.olMap.LetzterKlickHandler.deactivate() } markiertePop = waehleAusschnittFuerUebergebenePop(popListeMarkiert) // Grundkarte aufbauen $.when(zeigeFormular('olMap')).then(function () { // Karte zum richtigen Ausschnitt zoomen // aber nur, wenn keine Auswahl aktiv if (window.apf.olMap.auswahlPolygonLayer && window.apf.olMap.auswahlPolygonLayer.features.length > 0) { // Auswahl aktiv, Zoomstufe belassen } else { window.apf.olMap.map.updateSize() window.apf.olMap.map.getView().fitExtent(markiertePop.bounds, window.apf.olMap.map.getSize()) } // tpop und pop ergänzen // alle tpop holen $.ajax({ type: 'get', url: getApiHost() + '/tpopKarteAlle/apId=' + window.apf.ap.ApArtId }).done(function (tpopListe) { $.when( // Layer für Symbole und Beschriftung erstellen erstelleTPopLayer(tpopListe), // alle Pop holen, symbole und nr sichtbar schalten, Markierung übergeben zeigePopInTPop(true, markiertePop.popidMarkiert) ).then(function () { // layertree neu aufbauen initiiereLayertree() }) }).fail(function () { melde('Fehler: Es konnten keine Daten aus der Datenbank abgerufen werden') }) }) }
function getFeaturesFromRemote(requestOptions, viewer) { const requestResult = []; const requestPromises = getFeatureInfoRequests(requestOptions, viewer).map(request => request.fn.then((features) => { const layer = viewer.getLayer(request.layer); const map = viewer.getMap(); if (features) { features.forEach((feature) => { requestResult.push({ title: layer.get('title'), feature, content: getAttributes(feature, layer, map), layer: layer.get('name') }); }); return requestResult; } return false; })); return $.when(...requestPromises).then(() => requestResult); }
exports.getSummaryData = function(callback) { d1 = new $.Deferred(); d2 = new $.Deferred(); d3 = new $.Deferred(); d4 = new $.Deferred(); var result = []; getREM(); getMinera(); getIGas(); getFresnillo(); $.when(d1, d2, d3, d4).done(function(rem, minera, igas, fresnillo) { result.push(rem); result.push(minera); result.push(igas); result.push(fresnillo); callback(result); }); };
static loadItems() { return $.when([ { id: 1, name: "Apples", price: 10.99, itemType: 1 }, { id: 2, name: "Bananas", price: 20.99, itemType: 1 }, { id: 3, name: "Carrot", price: 1.99, itemType: 2 } ]); }
require(['app/utils/init', 'app/views/intro'], function(Initdb, IntroView) { APC.views.introView = new IntroView(); APC.views.introView.render(); APC.utils.initdb = new Initdb(); $.when(APC.utils.initdb).then(function(r) { APC.views.introView.progressBar(r.count, r.msg); setTimeout(function() { APC.router.navigate("inicio", { trigger: true }); }, 1000); }, function(err) { navigator.notification.alert('El repositorio de datos Open Data no está disponible ó se ha perdido la conexión con la red, inténtalo más tarde!', function() { Backbone.history.loadUrl("/"); }, 'Atención', 'Reintentar'); }, function(r) { APC.views.introView.progressBar(r.count, r.msg); }); });
show: function() { var iso = this.status.get('iso'); var shareOptions = { isCountry: true, iso: iso }; this.shareWindowView = new ShareWindowView(shareOptions); this._setVars(); this._setListeners(); $.when( this.countriesCollection.getCountriesList(), this.indicatorsCollection.getAllIndicatorsByCountry(iso) ).done(function() { this._renderBanner(); this._renderData(); }.bind(this)) },
app.put('/users/:id', ControllerAuth.admin, function(req, res) { var jsonModel = req.body; // If password change is requested, update the salt and hash var deferred = $.Deferred(); if (req.body.password) { logger.log('info', util.format('Admin[userId:%s] password change operation for user[%s]', req.session.user._id, jsonModel.id)); hash(req.body.password, function (err, salt, hash) { jsonModel = $.extend(jsonModel, { salt: salt, hash: hash }); deferred.resolve(); }); } else { deferred.resolve(); } $.when(deferred).done(function() { User.findById(req.params.id, function(err, user) { if (err) { return ControllerErrorHandler.handleError(req, res, err); } if (!user) { res.statusCode = 404; res.send(JSON.stringify({ code: res.statusCode, message: 'Error 404: user not found' })); } // Using Schema.save, not Schema.findByIdAndUpdate as only save // executes Schema.pre('save') // Mongoose issue: pre, post middleware are not executed on findByIdAndUpdate // https://github.com/LearnBoost/mongoose/issues/964 //User.findByIdAndUpdate(req.params.id, jsonModel, { new: true }, function(err, doc) { user = $.extend(user, jsonModel); user.save(function(err, doc) { if (err) { return ControllerErrorHandler.handleError(req, res, err); } res.send(JSON.stringify(doc)); }); }); }); });
getReport: function(appResource, action) { var reports = new schema.models.SpReport.LazyCollection({ filters: { appresource: appResource.id } }); var dataFetch = appResource.rget('spappresourcedatas', true); $.when(dataFetch, reports.fetch({ limit: 1 })).done(function(data) { if (data.length > 1) { console.warn("found multiple report definitions for appresource id:", appResource.id); } else if (data.length < 1) { console.error("couldn't find report definition for appresource id:", appResource.id); return; } if (!reports.isComplete()) { console.warn("found multiple report objects for appresource id:", appResource.id); } else if (reports.length < 1) { console.error("couldn't find report object for appresource id:", appResource.id); return; } var report = reports.at(0); var reportXML = data.at(0).get('data'); $.when(report.rget('query', true), fixupImages(reportXML)) .done(function(query, imageFixResult) { var reportResources = { appResource: appResource, report: report, reportXML: reportXML, query: query }; if (imageFixResult.isOK) { action(_({}).extend(reportResources, {reportXML: imageFixResult.reportXML})); } else new FixImagesDialog({ reportResources: reportResources, imageFixResult: imageFixResult, action: action }).render(); }); }); }
}).on('select2-selecting', function(event) { var styleUrl = '/static/vendor/bower_components/styles/' + event.val + '.csl'; var styleRequest = $.get(styleUrl); var citationRequest = $.get(ctx.node.urls.api + 'citation/'); $.when(styleRequest, citationRequest).done(function(style, data) { var citeproc = citations.makeCiteproc(style[0], data[0], 'text'); var items = citeproc.makeBibliography()[1]; self.$citationElement.text(items[0]).slideDown(); }).fail(function(jqxhr, status, error) { $osf.growl( 'Citation render failed', 'The requested citation format generated an error.', 'danger' ); Raven.captureMessage('Unexpected error when fetching citation', { url: styleUrl, citationStyle: event.val, status: status, error: error }); }); }).on('select2-removed', function(e) {
require(['app/views/sursur', 'app/collections/surAreas', 'app/collections/surSectores', 'app/collections/sursur'], function(sursurview, SurAreasCollection, SurSectoresCollection, sursurCollection) { if (typeof APC.collections.surAreasCollection === 'undefined') APC.collections.surAreasCollection = new SurAreasCollection(); if (typeof APC.collections.surSectoresCollection === 'undefined') APC.collections.surSectoresCollection = new SurSectoresCollection(); if (typeof APC.collections.sursurCollection === 'undefined') APC.collections.sursurCollection = new sursurCollection(); $.when(APC.collections.surAreasCollection.findAll(), APC.collections.surSectoresCollection.findAll(), APC.collections.sursurCollection.findAll()).done(function() { if (typeof APC.views.sursurview === 'undefined') APC.views.sursurview = new sursurview(); APC.views.sursurview.clearSelection(); APC.collections.sursurCollection.clearMarkers(); APC.collections.sursurCollection.initMapMarkers(); APC.views.sursurview.render(); }); });
var createActivityCard = function() { var activityCard = $(this); var href = activityCard.attr('data-path'); $.when(activities).done(function(activities) { var activity = activities[href]; displayActivity( activityCard, activity ); $.when(completions).done(function(completions) { var maxCompletion = 0; _.each( completions, function(c) { if (_.contains(activity.hashes, c.activityHash)) if (c.complete > maxCompletion) maxCompletion = c.complete; }); displayProgress( activityCard, maxCompletion ); }); }); };
getAsync: function () { var def = $.Deferred(); $.when(getSavedAsync(), getDefaultsAsync()) .done((savedResult, defaultsResult) => { // if savedResult has properties if (Object.getOwnPropertyNames(savedResult).length !== 0) { // return saved prefs: def.resolve(savedResult.userPrefs); } else { // save defaults and return those: _prefsUtils.saveAsync(defaultsResult) .done(() => { def.resolve(defaultsResult) }) .fail((res) => { throw new Error(res) }); } }); return def.promise(); },
next: function(tripIndex) { var that = this; var useDifferentIndex = !isNaN(tripIndex); // If we do give `tripIndex` here, it means that we want to directly jump // to that index no matter how. So in that case, ignore `canGoNext` check. if (!useDifferentIndex && !this.canGoNext()) { return; } this.tripDirection = 'next'; // This is te best timing to call tripEnd because no matter // users use arrow key or trip was changed by timer, we will // all be here. var tripObject = this.getCurrentTripObject(); var tripEnd = tripObject.onTripEnd || this.settings.onTripEnd; var tripEndDefer = tripEnd.call(this, this.tripIndex, tripObject); $.when(tripEndDefer).then(function() { if (useDifferentIndex) { if (that.timer) { that.timer.stop(); } that.setIndex(tripIndex); that.run(); return; } if (that.isLast()) { that.doLastOperation(); } else { that.increaseIndex(); that.run(); } }); },
execute: function(callback, args) { var self = this; if (!this.active) { // attach layout if columns if( this.columns ){ this.layout = new ColumnLayout({ columns: this.columns }); } this.triggerMethod.apply(this, ['before:enter'].concat(args)); } this.triggerMethod.apply(this, ['before:route'].concat(args)); $.when(this._execute(callback, args)).then(function() { if (!self.active) { self.triggerMethod.apply(self, ['enter'].concat(args)); } self.triggerMethod.apply(self, ['route'].concat(args)); }); },
this._pdScrollEnd = function(event){ if (self.$pdEle.hasClass('x-flip')) { self.$pdEle.removeClass('x-flip'); self.$pdEle.addClass('x-loading'); $pdlEle.text(self.pullDownLoadingLabel); var result = refreshCallback.call(this,event); if ($.type(result) === "object") { $.when(result).done(self.pullDownFinish()).fail(self.pullDownError()); } else if ($.type(result) === "boolean") { if (result) { self.pullDownFinish(event); } else { self.pullDownError(event); } } }else if(self.$pdEle.hasClass('x-restore')){ self.$pdEle.removeClass('x-restore'); self.$pdEle.addClass('x-pull-down'); this.refresh(); } };
var grab = function(url, selector) { $.when( graber(url) ).then( function(data, textStatus, jqXHR) { toastr.info(jqXHR.status, "jqXHR.status"); toastr.info(textStatus, "textStatus"); var content = $(data.results[0]); loader.clean(); if(content.find(selector).length) { var rawhtml = htmlcleaner(content.find(selector)[0].outerHTML); } else { toastr.error("I don't think that your selector is real", 'Inconceivable!') } $('#outhtml>code').text(rawhtml); hljs.highlightBlock($('#outhtml>code')[0]); htmlTree(rawhtml); }, function() { alert( "error" ); } ); };
google.maps.event.addListener(marker, 'click', function() { if (typeof APC.collections.demByMunicipios === 'undefined') APC.collections.demByMunicipios = new demandaByMunicipios(); APC.selection.demanda.cols['lat'] = []; APC.selection.demanda.cols['lat'].push(lat); APC.selection.demanda.cols['long'] = []; APC.selection.demanda.cols['long'].push(lng); APC.selection.demanda.cols['territorio'] = []; APC.selection.demanda.cols['territorio'].push(add); $.when(APC.collections.demByMunicipios.findByMunicipio()).done(function() { var modal = new modalView({ id: RowKey, title: add, collection: APC.collections.demByMunicipios }); modal.render(); }); });
_onSaveAllToCloud: function(e) { e.preventDefault(); // TODO: 'message' should be a property of this attachment model // TODO: 'folder' should be a property of the message model and so on var account = require('state').currentAccount; var folder = require('state').currentFolder; var messageId = this.message.get('id'); var saving = MessageController.saveAttachmentsToFiles(account, folder, messageId); // Loading feedback this.ui.saveAllToCloud.removeClass('icon-folder') .addClass('icon-loading-small') .prop('disabled', true); var _this = this; $.when(saving).always(function() { // Remove loading feedback again _this.ui.saveAllToCloud.addClass('icon-folder') .removeClass('icon-loading-small') .prop('disabled', false); }); }
prev: function() { var that = this; if (!this.canGoPrev()) { return; } this.tripDirection = 'prev'; // When this is executed, it means users click on the arrow key to // navigate back to previous trip. In that scenario, this is the better // place to call onTripEnd before modifying tripIndex. var tripObject = this.getCurrentTripObject(); var tripEnd = tripObject.onTripEnd || this.settings.onTripEnd; var tripEndDefer = tripEnd(this.tripIndex, tripObject); $.when(tripEndDefer).then(function() { if (!that.isFirst()) { that.decreaseIndex(); } that.run(); }); },
getEverything: function() { var self = this; return $.when( self.getWord(), self.getExamples(), self.getDefinitions(), self.getTopExample(), self.getRelatedWords(), self.getPronunciations(), self.getScrabbleScore(), self.getHyphenation(), self.getFrequency(), self.getPhrases(), self.getEtymologies(), self.getAudio() ) .then(function() { }) .fail(function() { console.log("failed!"); }); }
const renderTab = ({entity, tabConfig, customField, dom, context}) => { const adjustFrameSize = !tabConfig.frameTemplate || tabConfig.adjustFrameSize; const template = tabConfig.frameTemplate || defaultTemplate; const store = context.configurator.getStore(); when(getCustomFieldValue(store, entity, tabConfig.customFieldName)) .then(({value}) => innerRenderTab(dom, template, adjustFrameSize, { customField, value, entity })); const storeListener = onChange(store, entity, tabConfig.customFieldName, (changedValue) => innerRenderTab(dom, template, adjustFrameSize, { customField, value: changedValue, entity })); return { destroy: () => store.unbind(storeListener) }; };