Turbolinks and Drift Chat - turbolinks

I am using the Drift chat widget but it doesn't reload after the first page view.
Widget code is loaded in and I have set a reload function at each turbolinks reload
<head>
<script>
"use strict";
!function() {
var t = window.driftt = window.drift = window.driftt || [];
if (!t.init) {
if (t.invoked) return void (window.console && console.error && console.error("Drift snippet included twice."));
t.invoked = !0, t.methods = [ "identify", "config", "track", "reset", "debug", "show", "ping", "page", "hide", "off", "on" ],
t.factory = function(e) {
return function() {
var n = Array.prototype.slice.call(arguments);
return n.unshift(e), t.push(n), t;
};
}, t.methods.forEach(function(e) {
t[e] = t.factory(e);
}), t.load = function(t) {
var e = 3e5, n = Math.ceil(new Date() / e) * e, o = document.createElement("script");
o.type = "text/javascript", o.async = !0, o.crossorigin = "anonymous", o.src = "https://js.driftt.com/include/" + n + "/" + t + ".js";
var i = document.getElementsByTagName("script")[0];
i.parentNode.insertBefore(o, i);
};
}
}();
drift.SNIPPET_VERSION = '0.3.1';
drift.load('XXXXXXXXXXX');
drift.config({
enableWelcomeMessage: false,
locale: "<%=I18n.locale%>"
});
$(document).on("turbolinks:load", function(event) {
drift.on('ready',function(api){
drift.api.widget.show() <------- problem is here (?)
})
})
drift.on('ready',function(api){
console.log("Drift is ready")
$('.drift-open-chat').on('click', function(e){
api.widget.show()
api.sidebar.open()
e.preventDefault();
})
<% if current_user %>
drift.api.setUserAttributes({
user_id: <%=current_user.id%>,
email: "<%=current_user.email%>"
})
<% end %>
})
</script>

Drift expects the every navigation to be a full page reload, something that Turbolinks breaks. To fix the problem, you must add two permanent elements to your layout file. This will cause tubolinks to persist the chat widget from one body swap to another.
<div id="drift-frame-chat" class="drift-conductor-item drift-frame-chat" data-turbolinks-permanent></div>
<div id="drift-frame-controller" class="drift-conductor-item drift-frame-controller" data-turbolinks-permanent></div>
EDIT: It's been changed again.
Use the code below when changing pages to get it working correctly:
document.addEventListener('turbolinks:load',
() => {
if (window.drift.ready) {
window.drift.unload();
window.drift.load('{YOUR_EMBED_ID}');
}
})

Related

How to show dynamically multiple popup in openlayers 3 map

Can anyone tell me how to show all popup of markers in openlayers 3 map. I searched many sites but couldn't get any answer please anyone know about this then help me
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.TileJSON({
url: 'https://api.tiles.mapbox.com/v3/mapbox.geography-class.json?secure',
crossOrigin: 'anonymous'
})
})
],
overlays: [overlay],
target: 'map',
view: new ol.View({
center: ol.proj.fromLonLat([0, 50]),
zoom: 2
})
});
var vectorSource = new ol.source.Vector({
features: [
new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([16.37, 48.2])),
name: 'London'
}),
new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([-0.13, 51.51])),
name: 'NY'
}),
new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([30.69, 55.21])),
name: 'Paris'
})
]
});
var markers = new ol.layer.Vector({
source: vectorSource,
style: new ol.style.Style({
image: new ol.style.Icon({
src: '//openlayers.org/en/v3.12.1/examples/data/icon.png',
anchor: [0.5, 1]
})
})
});
map.addLayer(markers);
function showpopup(){
// For showing popups on Map
var arrayData = [1];
showInfoOnMap(map,arrayData,1);
function showInfoOnMap(map, arrayData, flag) {
var flag = 'show';
var extent = map.getView().calculateExtent(map.getSize());
var id = 0;
var element = document.getElementById('popup');
var popup = new ol.Overlay({
element: element,
positioning: 'center'
});
map.addOverlay(popup);
if (arrayData != null && arrayData.length > 0) {
arrayData.forEach(function(vectorSource) {
/* logMessage('vectorSource >> ' + vectorSource); */
if (vectorSource != null && markers.getSource().getFeatures() != null && markers.getSource().getFeatures().length > 0) {
markers.getSource().forEachFeatureInExtent(extent, function(feature) {
/* logMessage('vectorSource feature >> ' + feature); */
console.log("vectorSource feature >> " + markers.getSource().getFeatures());
if (flag == 'show') {
var geometry = feature.getGeometry();
var coord = geometry.getCoordinates();
popup.setPosition(coord);
/* var prop;
var vyprop = ""; */
$(element).popover({
'position': 'center',
'placement': 'top',
'template':'<div class="popover"><div class="popover-content"></div></div>',
'html': true,
'content': function() {
var string = [];
var st = feature.U.name;
if (st != null && st.length > 0) {
var arrayLength = 1;
string = "<table>";
string += '<tr><td>' + st + "</table>";
}
return string;
}
});
$(element).popover('show');
} else {
$(element).popover('destroy');
}
});
}
});
}
};
}
I used this code in my file but it show only one popup on all markers please someone tell me how to show all markers popup simultaneously.
I'm not sure exactly what you're trying to show in your popups, but I would probably try this approach. This extends the ol.Overlay class, allowing you to get the map object and attach a listener which you can use to grab the feature that was clicked. Is this what you're trying to accomplish?
function PopupOverlay() {
var element = document.createElement('div');
$(element).popover({
template: '<div class="popover"><div class="popover-content"></div></div>',
placement: 'top',
position: 'center',
html: true
});
ol.Overlay.call(this, {
element: element
});
}
ol.inherits(PopupOverlay, ol.Overlay);
PopupOverlay.prototype.setMap = function (map) {
var self = this;
map.on('singleclick', function (e) {
map.forEachFeatureAtPixel(e.pixel, function (feature, layer) {
ol.Overlay.prototype.setPosition.call(self, feature.getGeometry().getCoordinates());
var el = self.getElement();
$(el).data('bs.popover').options.content = function () {
// EDIT THE POPOVER CONTENT
return feature.get('name');
};
$(el).popover('show');
});
});
ol.Overlay.prototype.setMap.call(this, map);
};
Check out this example
So after your comment, I see what you're trying to do now. I would say that you want to take the same basic approach, make a class that overrides ol.Overlay, but this time just loop through all the features, creating an overlay for each feature.
This Updated Example
function PopoverOverlay(feature, map) {
this.feature = feature;
var element = document.createElement('div');
$(element).popover({
template: '<div class="popover"><div class="popover-content"></div></div>',
placement: 'top',
position: 'center',
html: true
});
ol.Overlay.call(this, {
element: element,
map: map
});
};
ol.inherits(PopoverOverlay, ol.Overlay);
PopoverOverlay.prototype.togglePopover = function () {
ol.Overlay.prototype.setPosition.call(this, this.feature.getGeometry().getCoordinates());
var self = this;
var el = this.getElement();
$(el).data('bs.popover').options.content = function () {
// EDIT THE POPOVER CONTENT
return self.feature.get('name');
};
$(el).popover('toggle');
};
// create overlays for each feature
var overlays = (function createOverlays () {
var popupOverlays = [];
vectorSource.getFeatures().forEach(function (feature) {
var overlay = new PopoverOverlay(feature, map);
popupOverlays.push(overlay);
map.addOverlay(overlay);
});
return popupOverlays;
})();
// on click, toggle the popovers
map.on('singleclick', function () {
for(var i in overlays) {
overlays[i].togglePopover();
}
});
Now when you click anywhere on the map, it should call the togglePopover method and toggle the popover on the individual element.

ui-select encapsulated in a directive

I am trying to abstract few things specific to my project into a directive built on top of ui-select. I am running into a basic issue where the ui-select directive doesn't respond to any scope changes from with in my directive.
Weird part is watching for the same variables in my directive shows that values indeed are changing.
Here is the most stripped down plunker: http://plnkr.co/edit/8J3aMK1YMIIsJC3oa56U
Appreciate any help.
'use strict';
var app = angular.module('demo', ['ngSanitize', 'ui.select']);
app.controller('DemoCtrl', function($scope, $http, $timeout) {
$scope.multipleDemo = {};
$scope.disabled = undefined;
$scope.enable = function() {
$scope.disabled = false;
};
$scope.disable = function() {
$scope.disabled = true;
};
});
app.directive('tagEditor', [function() {
return {
restrict: 'A',
//replace: true,
templateUrl: 'tagEditor.html',
scope: {
isDisabled: '#',
tags: '='
},
link: function(scope, elem, attrs) {
scope.$watch('isDisabled', function(newVal, oldVal) {
console.log('isDisabled watch fired with values ' + newVal + ',' + oldVal);
console.log('isDisabled value is ' + scope.isDisabled + ' and type is ' + typeof scope.isDisabled);
});
scope.$watch('tags', function(newVal, oldVal) {
console.log('tags watch fired with values ' + newVal + oldVal);
});
}
};
}]);

React JS setState({dict : dict })

I wonder if this is the correct solution to update the state with two dictionares
var PopulationCityView = React.createClass({
getInitialState: function() {
return {
prod_diff : {'wheat':0,'meat':0,'fish':0,'bread':0,'fruit':0,'wine':0,'beer':0,'wool':0,'cloth':0,'leather':0,'paper':0,'ceramics':0,'furniture':0,'glass':0}
};
},
componentWillMount: function() {
this.prod_diff = {'wheat':0,'meat':0,'fish':0,'bread':0,'fruit':0,'wine':0,'beer':0,'wool':0,'cloth':0,'leather':0,'paper':0,'ceramics':0,'furniture':0,'glass':0};
},
handleM: function(res,child_new_res_diff){
var new_prod_diff = this.prod_diff;
new_prod_diff[res] = child_new_res_diff;
this.setState({prod_diff:new_prod_diff});
},
render: function(){
........
if anyone knows of a better and faster solution would ask for a hint...
Much safer and more efficient way is to keep your state as simple object with primitive values:
var PopulationCityView = React.createClass({
getInitialState: function() {
return {
wheat: 0,
meat: 0,
fish: 0,
};
},
handleM: function(res,child_new_res_diff){
var new_state = {};
new_state[res] = child_new_res_diff;
this.setState(new_state);
},
render: function() { /* your render code */ }
});
If you really have to store your values in nested object you have to remember to clone nested object before modifying it:
var PopulationCityView = React.createClass({
getInitialState: function() {
return {
prod_diff: { wheat: 0, meat: 0, fish: 0 }
};
},
handleM: function(res,child_new_res_diff){
var new_prod_diff = _.clone(this.state.prod_diff);
new_prod_diff[res] = child_new_res_diff;
this.setState({ prod_diff: new_prod_diff });
},
render: function() { /* your render code */ }
});
I've made your initial state a little smaller to simplify code examples.
Also consider using React Immutability Helpers which makes operating on nested objects inside state safer.
I forgot to add that handleM function arguments are sent by the child.
In my solution it does not work smoothly (slider that adjusts the prod_diff jams), the same effect is when I apply the solution #daniula
Now I have decided to make use of CortexJS and everything runs smoothly
I would ask to correct me if I used this library incorrectly:
PARENT
var PopulationCityView = React.createClass({
getInitialState: function() {
return {
prod_diff_C : new Cortex({'wheat':0,'meat':0,'fish':0,'bread':0,'fruit':0,'wine':0,'beer':0,'wool':0,'cloth':0,'leather':0,'paper':0,'ceramics':0,'furniture':0,'glass':0}),
};
},
componentWillUnmount: function() {
delete this.state.prod_diff_C;
},
componentDidMount: function(){
var that = this;
this.state.prod_diff_C.on("update",function (updatedRes) {that.setState({prod_diff_C: updatedRes});});
},
// handleM: function(res,child_new_res_diff){
// var new_prod_diff = this.prod_diff;
// new_prod_diff[res] = -child_new_res_diff;
// this.setState(new_prod_diff);
// },
render: function(){
var foods = {}, goods = {};
for(var g = 0; g< this.goods.length; g++){
R = this.goods[g];
goods[R] = <div style={{display:"inline-block"}}>
<CHILD_1 res_par={this.props.data.res_uses[R]} res={R} prod_diff_cortex={this.state.prod_diff_C}/>
<SLIDER prod_diff_cortex={this.state.prod_diff_C} res={R} res_have={this.props.data.res_uses[R][0]} res_need={this.props.data.res_uses[R][1]} />
</div>
}
}
return ( .... )
}
})
CHILD_1
var CHILD_1 = React.createClass({
render: function(){
var val = this.props.res_par[3] + this.props.prod_diff_cortex[this.props.res].getValue()
return (
<div className='population-production-upkeep'>
{val}
</div>
)
}
})
SLIDER
var SLIDER= React.createClass({
......
handleMouseDown: function(event){
var start_val = this.props.res_have + this.props.prod_diff_cortex[this.props.res].getValue()
this.val_start = start_val;
this.res_diff_start = this.props.prod_diff_cortex[this.props.res].getValue()
this.touched = 1;
this.pos_start_x = event.screenX;
this.prev_pos_x = this.width_step * start_val;
event.stopPropagation();
event.preventDefault();
},
handleMouseMove: function(event){
if(this.touched) {
var x_diff = event.screenX - this.pos_start_x ;
var x = this.prev_pos_x + x_diff;
if (x < 0) x = 0;
if (x > this.state.max_pos_x) x = this.state.max_pos_x;
var stor = Math.round(x* 100 / this.width_step ) / 100
var new_res_diff = this.res_diff_start + stor - this.val_start;
this.props.prod_diff_cortex[this.props.res].set(new_res_diff)
}
},
......
render: function() {
var val = Math.round((this.props.res_have+this.props.prod_diff_cortex[this.props.res].getValue())*100)/100;
return (
..../* slider render */
);
}
});

MeteorJS: Collection.find fires multiple times instead of once

I have an app that when you select an industry from a drop down list a collection is updated where the attribute equals the selected industry.
JavaScript:
Template.selector.events({
'click div.select-block ul.dropdown-menu li': function(e) {
var selectedIndex = $(e.currentTarget).attr("rel");
var val = $('select#industryPicker option:eq(' + selectedIndex + ')').attr('value');
var oldVal = Session.get('currentIndustryOnet');
if(val != oldVal) {
Session.set('jobsLoaded', false);
Session.set('currentIndustryOnet', val);
Meteor.call('countByOnet', val, function(error, results){
if(results > 0) {
Session.set('jobsLoaded', true);
} else {
getJobsByIndustry(val);
}
});
}
}
});
var getJobsByIndustry = function(onet) {
if(typeof(onet) === "undefined")
alert("Must include an Onet code");
var params = "onet=" + onet + "&cn=100&rs=1&re=500";
return getJobs(params, onet);
}
var getJobs = function(params, onet) {
Meteor.call('retrieveJobs', params, function(error, results){
$('job', results.content).each(function(){
var jvid = $(this).find('jvid').text();
var job = Jobs.findOne({jvid: jvid});
if(!job) {
options = {}
options.title = $(this).find('title').text();
options.company = $(this).find('company').text();
options.address = $(this).find('location').text();
options.jvid = jvid;
options.onet = onet;
options.url = $(this).find('url').text();
options.dateacquired = $(this).find('dateacquired').text();
var id = createJob(options);
console.log("Job Created: " + id);
}
});
Session.set('jobsLoaded', true);
});
}
Template.list.events({
'click div.select-block ul.dropdown-menu li': function(e){
var selectedIndex = $(e.currentTarget).attr("rel");
var val = $('select#perPage option:eq(' + selectedIndex + ')').attr('value');
var oldVal = Session.get('perPage');
if(val != oldVal) {
Session.set('perPage', val);
Pagination.perPage(val);
}
}
});
Template.list.jobs = function() {
var jobs;
if(Session.get('currentIndustryOnet')) {
jobs = Jobs.find({onet: Session.get('currentIndustryOnet')}).fetch();
var addresses = _.chain(jobs)
.countBy('address')
.pairs()
.sortBy(function(j) {return -j[1];})
.map(function(j) {return j[0];})
.first(100)
.value();
gmaps.clearMap();
$.each(_.uniq(addresses), function(k, v){
var addr = v.split(', ');
Meteor.call('getCity', addr[0].toUpperCase(), addr[1], function(error, city){
if(city) {
var opts = {};
opts.lng = city.loc[1];
opts.lat = city.loc[0];
opts.population = city.pop;
gmaps.addMarker(opts);
}
});
})
return Pagination.collection(jobs);
} else {
jobs = Jobs.find()
Session.set('jobCount', jobs.count());
return Pagination.collection(jobs.fetch());
}
}
In Template.list.jobs if you console.log(addresses), it is called 4 different times. The browser console looks like this:
(2) 100
(2) 100
Any reason why this would fire multiple times?
As #musically_ut said it might be because of your session data.
Basically you must make the difference between reactive datasources and non reactive datasources.
Non reactive are standard javascript, nothing fancy.
The reactive ones however are monitored by Meteor and when one is updated (insert, update, delete, you name it), Meteor is going to execute again all parts which uses this datasource. Default reactive datasources are: collections and sessions. You can also create yours.
So when you update your session attribute, it is going to execute again all helper's methods which are using this datasource.
About the rendering, pages were rendered again in Meteor < 0.8, now with Blaze it is not the case anymore.
Here is a quick example for a better understanding:
The template first
<head>
<title>test</title>
</head>
<body>
{{> hello}}
</body>
<template name="hello">
<h1>{{getSession}}</h1>
<h1>{{getNonReactiveSession}}</h1>
<h1>{{getCollection}}</h1>
<input type="button" name="session" value="Session" />
<input type="button" name="collection" value="Collection" />
</template>
And the client code
if (Meteor.isClient) {
CollectionWhatever = new Meteor.Collection;
Template.hello.events({
'click input[name="session"]': function () {
Session.set('date', new Date());
},
'click input[name="collection"]': function () {
CollectionWhatever.insert({});
}
});
Template.hello.getSession = function () {
console.log('getSession');
return Session.get('date');
};
Template.hello.getNonReactiveSession = function () {
console.log('getNonReactiveSession');
var sessionVal = null;
new Deps.nonreactive(function () {
sessionVal = Session.get('date');
});
return sessionVal;
};
Template.hello.getCollection = function () {
console.log('getCollection');
return CollectionWhatever.find().count();
};
Template.hello.rendered = function () {
console.log('rendered');
}
}
If you click on a button it is going to update a datasource and the helper method which is using this datasource will be executed again.
Except for the non reactive session, with Deps.nonreactive you can make Meteor ignore the updates.
Do not hesitate to add logs to your app!
You can read:
Reactivity
Dependencies

Best way to load css for partial views loaded using ajax

I'm working on my application that creates tabs dynamically and fills them with partial views using ajax.
My question is: how to load css for this views? What's the best way to do it? I mean I can't load the css file on the partial view (no head) or could i?
Some code: the tabManager (a partial view loaded on the main page):
<script>
var tabTemplate = "<li class='#{color}'><a id='#{id}'href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>"; // base format for the tabs
$(document).ready(function () {
var tabs = $("#tabs").tabs(); // apply jQuery ui to tabs
$("a.menuButton").click(function () {
var urlContent = $(this).data("direction");
var label = $(this).data("label");
var idTab = $(this).data("id");
var color = $(this).data("color");
var exist = false;
var counter = 0;
$('#tabs ul li a').each(function (i) { // tab already exist o no hay que crear una tabla?
counter = counter + 1; // index counter
if (this.id == "#" + idTab) { // Tab already exist?
exist = true;
$("#tabs").tabs("option", "active", counter - 1); //activate existing element
}
});
if (idTab == "-1") { // is a clickable element?
exist = true;
}
if (exist == false) { // create new tab
addTab(idTab, label, color); // basic tab
getTabContent(idTab, urlContent); // content for new tab
var lastTab = $('#tabs >ul >li').size() - 1; // get count of tabs
$("#tabs").tabs("option", "active", lastTab); // select last created tab
}
});
function getTabContent(idT, urlC) { // ajax call to partial view
$.ajax({
url: urlC,
type: 'GET',
async: false,
success: function (result) {
$("#"+idT).html(result);
}
});
};
function addTab(idT, labT, color) { //create new tab
var label = labT,
id = idT,
li = $(tabTemplate.replace(/#\{href\}/g, "#" + id).replace(/#\{label\}/g, label).replace(/#\{id\}/g, "#" + id).replace(/#\{color\}/g, color)),
tabContentHtml = "Cargando...";
tabs.find(".ui-tabs-nav").append(li);
tabs.append("<div id='" + id + "'><p>" + tabContentHtml + "</p></div>");
tabs.tabs("refresh");
}
// close icon: removing the tab on click
tabs.delegate("span.ui-icon-close", "click", function () {
var panelId = $(this).closest("li").remove().attr("aria-controls");
$("#" + panelId).remove();
tabs.tabs("refresh");
});
tabs.bind("keyup", function (event) {
if (event.altKey && event.keyCode === $.ui.keyCode.BACKSPACE) {
var panelId = tabs.find(".ui-tabs-active").remove().attr("aria-controls");
$("#" + panelId).remove();
tabs.tabs("refresh");
}
});
});
</script>
<div id=tabs>
<ul>
</ul>
A button example:
<li><a class="menuButton" href="#" title="Permisos" data-id="tab3" data-direction="Permiso/_Administrar" data-label="Label" data-color="blue"><img src="#Res_icons.More">Permisos</a><li>
i found my answer here: http://dean.resplace.net/blog/2012/09/jquery-load-css-with-ajax-all-browsers/
the code:
<script type="text/javascript">
$(document).ready(function () {
$("head").append("<link href='...' rel='stylesheet'>");
});
</script>

Resources