I have wrote a simple application that have two views, the first view load google search engine ui.
I have two routes, search route and home route, and I load the search route for the first time, it works well, but when I change route and to home and back to the search route, the search view will not work.
SearchView code:
var SearchView = Marionette.View.extend({
template: "#search-template",
onRender: function() {
var cx = '010767762450613121260:fzszywg7ozm';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = this.$el.find("#googleResult")[0];
s.prepend(gcse);
},
events: {
'click button': 'doSearch'
},
doSearch: function(e) {
var input = document.getElementById('search-box-id');
var element = google.search.cse.element.getElement('searchresults-only0');
if (input.value == '') {
element.clearAllResults();
} else {
element.execute(input.value);
}
log("Search for ");
}
});
this is the code: https://jsfiddle.net/kk266551/29/
Thanks.
I console I get such error:
Uncaught TypeError: Cannot read property 'execute' of null
at n.doSearch ((index):127)
This it that line: element.execute(input.value);
It means that it doesn't find element searchresults-only0
on next render.
On next render element's name should be searchresults-only1
and so on.
I tired to fix that by giving gname https://developers.google.com/custom-search/docs/element#gname and searching element by it but it didn't work either.
At last I found that the problem is that on each render Google script is reloaded and conflicts with itself.
So that's what I did in your script that made it work as expected:
<gcse:searchresults-only gname="other"></gcse:searchresults-only>
onRender: function() {
// check if Google script was loaded at least once
if(!window.google) {
var cx = '010767762450613121260:fzszywg7ozm';
// saving gcse to global object
var gcse = window.gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
}
var s = this.$el.find(".googleResult").last();
s.prepend(window.gcse);
},
doSearch: function(e) {
var input = document.getElementById('search-box-id');
var element = google.search.cse.element.getElement('other');
if (input.value == '') {
element.clearAllResults();
} else {
element.execute(input.value);
}
log("Search for ");
}
You owe few bucks for some homeless man in a street.