run websocket-rails javascript client in node.js - javascript

I'm trying to retrieve data from a websocket using my own web server. The websocket server on the remote host runs websocket-rails. From the Websocket-rails github project page (https://github.com/websocket-rails) I used the javascript client code to put together a web socket client in a html file. That is, I copied the contents of all CoffeeScript files in /lib/assets/javascripts/websocket_rails on github to a single file and then compiled it with js2coffee.org (probably better solutions, but i'm quite a noob as you may have noticed by now). Then added a few lines to connect to the remote web socket and subscribe to a channel. (the channel part is actually why I use the Websocket-rails client, instead of a "normal" web socket connection. As I couldn't figure out how to subscribe to a channel after connecting through a "normal" websocket connection.)
so far so good. When I I use a browser and the code below, I can connect to a channel from the websocket on the remote host and the messages are send to the console.
<!DOCTYPE html>
<meta charset="utf-8" />
<title>WebSocket Test</title>
<script language="javascript" type="text/javascript">
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
this.WebSocketRails = (function() {
function WebSocketRails(url, use_websockets) {
this.url = url;
this.use_websockets = use_websockets != null ? use_websockets : true;
this.connection_stale = __bind(this.connection_stale, this);
this.pong = __bind(this.pong, this);
this.supports_websockets = __bind(this.supports_websockets, this);
this.dispatch_channel = __bind(this.dispatch_channel, this);
this.unsubscribe = __bind(this.unsubscribe, this);
this.subscribe_private = __bind(this.subscribe_private, this);
this.subscribe = __bind(this.subscribe, this);
this.dispatch = __bind(this.dispatch, this);
this.trigger_event = __bind(this.trigger_event, this);
this.trigger = __bind(this.trigger, this);
this.unbind = __bind(this.unbind, this);
this.bind = __bind(this.bind, this);
this.connection_established = __bind(this.connection_established, this);
this.new_message = __bind(this.new_message, this);
this.reconnect = __bind(this.reconnect, this);
this.callbacks = {};
this.channels = {};
this.queue = {};
this.connect();
}
WebSocketRails.prototype.connect = function() {
this.state = 'connecting';
if (!(this.supports_websockets() && this.use_websockets)) {
this._conn = new WebSocketRails.HttpConnection(this.url, this);
} else {
this._conn = new WebSocketRails.WebSocketConnection(this.url, this);
}
return this._conn.new_message = this.new_message;
};
WebSocketRails.prototype.disconnect = function() {
if (this._conn) {
this._conn.close();
delete this._conn._conn;
delete this._conn;
}
return this.state = 'disconnected';
};
WebSocketRails.prototype.reconnect = function() {
var event, id, old_connection_id, _ref, _ref1;
old_connection_id = (_ref = this._conn) != null ? _ref.connection_id : void 0;
this.disconnect();
this.connect();
_ref1 = this.queue;
for (id in _ref1) {
event = _ref1[id];
if (event.connection_id === old_connection_id && !event.is_result()) {
this.trigger_event(event);
}
}
return this.reconnect_channels();
};
WebSocketRails.prototype.new_message = function(data) {
var event, socket_message, _i, _len, _ref, _results;
_results = [];
for (_i = 0, _len = data.length; _i < _len; _i++) {
socket_message = data[_i];
event = new WebSocketRails.Event(socket_message);
if (event.is_result()) {
if ((_ref = this.queue[event.id]) != null) {
_ref.run_callbacks(event.success, event.data);
}
delete this.queue[event.id];
} else if (event.is_channel()) {
this.dispatch_channel(event);
} else if (event.is_ping()) {
this.pong();
} else {
this.dispatch(event);
}
if (this.state === 'connecting' && event.name === 'client_connected') {
_results.push(this.connection_established(event.data));
} else {
_results.push(void 0);
}
}
return _results;
};
WebSocketRails.prototype.connection_established = function(data) {
this.state = 'connected';
this._conn.setConnectionId(data.connection_id);
this._conn.flush_queue();
if (this.on_open != null) {
return this.on_open(data);
}
};
WebSocketRails.prototype.bind = function(event_name, callback) {
var _base;
if ((_base = this.callbacks)[event_name] == null) {
_base[event_name] = [];
}
return this.callbacks[event_name].push(callback);
};
WebSocketRails.prototype.unbind = function(event_name) {
return delete this.callbacks[event_name];
};
WebSocketRails.prototype.trigger = function(event_name, data, success_callback, failure_callback) {
var event, _ref;
event = new WebSocketRails.Event([event_name, data, (_ref = this._conn) != null ? _ref.connection_id : void 0], success_callback, failure_callback);
return this.trigger_event(event);
};
WebSocketRails.prototype.trigger_event = function(event) {
var _base, _name;
if ((_base = this.queue)[_name = event.id] == null) {
_base[_name] = event;
}
if (this._conn) {
this._conn.trigger(event);
}
return event;
};
WebSocketRails.prototype.dispatch = function(event) {
var callback, _i, _len, _ref, _results;
if (this.callbacks[event.name] == null) {
return;
}
_ref = this.callbacks[event.name];
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
callback = _ref[_i];
_results.push(callback(event.data));
}
return _results;
};
WebSocketRails.prototype.subscribe = function(channel_name, success_callback, failure_callback) {
var channel;
if (this.channels[channel_name] == null) {
channel = new WebSocketRails.Channel(channel_name, this, false, success_callback, failure_callback);
this.channels[channel_name] = channel;
return channel;
} else {
return this.channels[channel_name];
}
};
WebSocketRails.prototype.subscribe_private = function(channel_name, success_callback, failure_callback) {
var channel;
if (this.channels[channel_name] == null) {
channel = new WebSocketRails.Channel(channel_name, this, true, success_callback, failure_callback);
this.channels[channel_name] = channel;
return channel;
} else {
return this.channels[channel_name];
}
};
WebSocketRails.prototype.unsubscribe = function(channel_name) {
if (this.channels[channel_name] == null) {
return;
}
this.channels[channel_name].destroy();
return delete this.channels[channel_name];
};
WebSocketRails.prototype.dispatch_channel = function(event) {
if (this.channels[event.channel] == null) {
return;
}
return this.channels[event.channel].dispatch(event.name, event.data);
};
WebSocketRails.prototype.supports_websockets = function() {
return typeof WebSocket === "function" || typeof WebSocket === "object";
};
WebSocketRails.prototype.pong = function() {
var pong, _ref;
pong = new WebSocketRails.Event(['websocket_rails.pong', {}, (_ref = this._conn) != null ? _ref.connection_id : void 0]);
return this._conn.trigger(pong);
};
WebSocketRails.prototype.connection_stale = function() {
return this.state !== 'connected';
};
WebSocketRails.prototype.reconnect_channels = function() {
var callbacks, channel, name, _ref, _results;
_ref = this.channels;
_results = [];
for (name in _ref) {
channel = _ref[name];
callbacks = channel._callbacks;
channel.destroy();
delete this.channels[name];
channel = channel.is_private ? this.subscribe_private(name) : this.subscribe(name);
channel._callbacks = callbacks;
_results.push(channel);
}
return _results;
};
return WebSocketRails;
})();
/*
The Event object stores all the relevant event information.
*/
WebSocketRails.Event = (function() {
function Event(data, success_callback, failure_callback) {
var attr;
this.success_callback = success_callback;
this.failure_callback = failure_callback;
this.name = data[0];
attr = data[1];
if (attr != null) {
this.id = attr['id'] != null ? attr['id'] : ((1 + Math.random()) * 0x10000) | 0;
this.channel = attr.channel != null ? attr.channel : void 0;
this.data = attr.data != null ? attr.data : attr;
this.token = attr.token != null ? attr.token : void 0;
this.connection_id = data[2];
if (attr.success != null) {
this.result = true;
this.success = attr.success;
}
}
}
Event.prototype.is_channel = function() {
return this.channel != null;
};
Event.prototype.is_result = function() {
return typeof this.result !== 'undefined';
};
Event.prototype.is_ping = function() {
return this.name === 'websocket_rails.ping';
};
Event.prototype.serialize = function() {
return JSON.stringify([this.name, this.attributes()]);
};
Event.prototype.attributes = function() {
return {
id: this.id,
channel: this.channel,
data: this.data,
token: this.token
};
};
Event.prototype.run_callbacks = function(success, result) {
this.success = success;
this.result = result;
if (this.success === true) {
return typeof this.success_callback === "function" ? this.success_callback(this.result) : void 0;
} else {
return typeof this.failure_callback === "function" ? this.failure_callback(this.result) : void 0;
}
};
return Event;
})();
/*
Abstract Interface for the WebSocketRails client.
*/
WebSocketRails.AbstractConnection = (function() {
function AbstractConnection(url, dispatcher) {
this.dispatcher = dispatcher;
this.message_queue = [];
}
AbstractConnection.prototype.close = function() {};
AbstractConnection.prototype.trigger = function(event) {
if (this.dispatcher.state !== 'connected') {
return this.message_queue.push(event);
} else {
return this.send_event(event);
}
};
AbstractConnection.prototype.send_event = function(event) {
if (this.connection_id != null) {
return event.connection_id = this.connection_id;
}
};
AbstractConnection.prototype.on_close = function(event) {
var close_event;
if (this.dispatcher && this.dispatcher._conn === this) {
close_event = new WebSocketRails.Event(['connection_closed', event]);
this.dispatcher.state = 'disconnected';
return this.dispatcher.dispatch(close_event);
}
};
AbstractConnection.prototype.on_error = function(event) {
var error_event;
if (this.dispatcher && this.dispatcher._conn === this) {
error_event = new WebSocketRails.Event(['connection_error', event]);
this.dispatcher.state = 'disconnected';
return this.dispatcher.dispatch(error_event);
}
};
AbstractConnection.prototype.on_message = function(event_data) {
if (this.dispatcher && this.dispatcher._conn === this) {
return this.dispatcher.new_message(event_data);
}
};
AbstractConnection.prototype.setConnectionId = function(connection_id) {
this.connection_id = connection_id;
};
AbstractConnection.prototype.flush_queue = function() {
var event, _i, _len, _ref;
_ref = this.message_queue;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
event = _ref[_i];
this.trigger(event);
}
return this.message_queue = [];
};
return AbstractConnection;
})();
/*
HTTP Interface for the WebSocketRails client.
*/
WebSocketRails.HttpConnection = (function(_super) {
__extends(HttpConnection, _super);
HttpConnection.prototype.connection_type = 'http';
HttpConnection.prototype._httpFactories = function() {
return [
function() {
return new XDomainRequest();
}, function() {
return new XMLHttpRequest();
}, function() {
return new ActiveXObject("Msxml2.XMLHTTP");
}, function() {
return new ActiveXObject("Msxml3.XMLHTTP");
}, function() {
return new ActiveXObject("Microsoft.XMLHTTP");
}
];
};
function HttpConnection(url, dispatcher) {
var e;
this.dispatcher = dispatcher;
HttpConnection.__super__.constructor.apply(this, arguments);
this._url = "http://" + url;
this._conn = this._createXMLHttpObject();
this.last_pos = 0;
try {
this._conn.onreadystatechange = (function(_this) {
return function() {
return _this._parse_stream();
};
})(this);
this._conn.addEventListener("load", this.on_close, false);
} catch (_error) {
e = _error;
this._conn.onprogress = (function(_this) {
return function() {
return _this._parse_stream();
};
})(this);
this._conn.onload = this.on_close;
this._conn.readyState = 3;
}
this._conn.open("GET", this._url, true);
this._conn.send();
}
HttpConnection.prototype.close = function() {
return this._conn.abort();
};
HttpConnection.prototype.send_event = function(event) {
HttpConnection.__super__.send_event.apply(this, arguments);
return this._post_data(event.serialize());
};
HttpConnection.prototype._post_data = function(payload) {
return $.ajax(this._url, {
type: 'POST',
data: {
client_id: this.connection_id,
data: payload
},
success: function() {}
});
};
HttpConnection.prototype._createXMLHttpObject = function() {
var e, factories, factory, xmlhttp, _i, _len;
xmlhttp = false;
factories = this._httpFactories();
for (_i = 0, _len = factories.length; _i < _len; _i++) {
factory = factories[_i];
try {
xmlhttp = factory();
} catch (_error) {
e = _error;
continue;
}
break;
}
return xmlhttp;
};
HttpConnection.prototype._parse_stream = function() {
var data, e, event_data;
if (this._conn.readyState === 3) {
data = this._conn.responseText.substring(this.last_pos);
this.last_pos = this._conn.responseText.length;
data = data.replace(/\]\]\[\[/g, "],[");
try {
event_data = JSON.parse(data);
return this.on_message(event_data);
} catch (_error) {
e = _error;
}
}
};
return HttpConnection;
})(WebSocketRails.AbstractConnection);
/*
WebSocket Interface for the WebSocketRails client.
*/
WebSocketRails.WebSocketConnection = (function(_super) {
__extends(WebSocketConnection, _super);
WebSocketConnection.prototype.connection_type = 'websocket';
function WebSocketConnection(url, dispatcher) {
this.url = url;
this.dispatcher = dispatcher;
WebSocketConnection.__super__.constructor.apply(this, arguments);
if (this.url.match(/^wss?:\/\//)) {
console.log("WARNING: Using connection urls with protocol specified is depricated");
} else if (window.location.protocol === 'https:') {
this.url = "wss://" + this.url;
} else {
this.url = "wss://" + this.url;
}
this._conn = new WebSocket(this.url);
this._conn.onmessage = (function(_this) {
return function(event) {
var event_data;
event_data = JSON.parse(event.data);
return _this.on_message(event_data);
};
})(this);
this._conn.onclose = (function(_this) {
return function(event) {
return _this.on_close(event);
};
})(this);
this._conn.onerror = (function(_this) {
return function(event) {
return _this.on_error(event);
};
})(this);
}
WebSocketConnection.prototype.close = function() {
return this._conn.close();
};
WebSocketConnection.prototype.send_event = function(event) {
WebSocketConnection.__super__.send_event.apply(this, arguments);
return this._conn.send(event.serialize());
};
return WebSocketConnection;
})(WebSocketRails.AbstractConnection);
/*
The channel object is returned when you subscribe to a channel.
For instance:
var dispatcher = new WebSocketRails('localhost:3000/websocket');
var awesome_channel = dispatcher.subscribe('awesome_channel');
awesome_channel.bind('event', function(data) { console.log('channel event!'); });
awesome_channel.trigger('awesome_event', awesome_object);
If you want to unbind an event, you can use the unbind function :
awesome_channel.unbind('event')
*/
WebSocketRails.Channel = (function() {
function Channel(name, _dispatcher, is_private, on_success, on_failure) {
var event, event_name, _ref;
this.name = name;
this._dispatcher = _dispatcher;
this.is_private = is_private != null ? is_private : false;
this.on_success = on_success;
this.on_failure = on_failure;
this._failure_launcher = __bind(this._failure_launcher, this);
this._success_launcher = __bind(this._success_launcher, this);
this._callbacks = {};
this._token = void 0;
this._queue = [];
if (this.is_private) {
event_name = 'websocket_rails.subscribe_private';
} else {
event_name = 'websocket_rails.subscribe';
}
this.connection_id = (_ref = this._dispatcher._conn) != null ? _ref.connection_id : void 0;
event = new WebSocketRails.Event([
event_name, {
data: {
channel: this.name
}
}, this.connection_id
], this._success_launcher, this._failure_launcher);
this._dispatcher.trigger_event(event);
}
Channel.prototype.destroy = function() {
var event, event_name, _ref;
if (this.connection_id === ((_ref = this._dispatcher._conn) != null ? _ref.connection_id : void 0)) {
event_name = 'websocket_rails.unsubscribe';
event = new WebSocketRails.Event([
event_name, {
data: {
channel: this.name
}
}, this.connection_id
]);
this._dispatcher.trigger_event(event);
}
return this._callbacks = {};
};
Channel.prototype.bind = function(event_name, callback) {
var _base;
if ((_base = this._callbacks)[event_name] == null) {
_base[event_name] = [];
}
return this._callbacks[event_name].push(callback);
};
Channel.prototype.unbind = function(event_name) {
return delete this._callbacks[event_name];
};
Channel.prototype.trigger = function(event_name, message) {
var event;
event = new WebSocketRails.Event([
event_name, {
channel: this.name,
data: message,
token: this._token
}, this.connection_id
]);
if (!this._token) {
return this._queue.push(event);
} else {
return this._dispatcher.trigger_event(event);
}
};
Channel.prototype.dispatch = function(event_name, message) {
var callback, _i, _len, _ref, _ref1, _results;
if (event_name === 'websocket_rails.channel_token') {
this.connection_id = (_ref = this._dispatcher._conn) != null ? _ref.connection_id : void 0;
this._token = message['token'];
return this.flush_queue();
} else {
if (this._callbacks[event_name] == null) {
return;
}
_ref1 = this._callbacks[event_name];
_results = [];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
callback = _ref1[_i];
_results.push(callback(message));
}
return _results;
}
};
Channel.prototype._success_launcher = function(data) {
if (this.on_success != null) {
return this.on_success(data);
}
};
Channel.prototype._failure_launcher = function(data) {
if (this.on_failure != null) {
return this.on_failure(data);
}
};
Channel.prototype.flush_queue = function() {
var event, _i, _len, _ref;
_ref = this._queue;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
event = _ref[_i];
this._dispatcher.trigger_event(event);
}
return this._queue = [];
};
return Channel;
})();
}).call(this);
//// Below is the code I added, the rest is compiled coffeeScript from the WebSocket-Rails github repository
testWebSocket = function() {
var channelTicker, websocket;
websocket = new WebSocketRails(wsUri);
websocket.on_open = function(data) {
console.log("Socket opened on " + wsUri + " :)");
};
channelTicker = websocket.subscribe("ticker");
channelTicker.bind("ticker.new", function(data) {
console.log(data);
});
};
wsUri = "ws.remotehost.com:3456/websocket";
testWebSocket();
</script>
<h2>WebSocket Test</h2>
<p>all output in console</p>
So after this I thought, nice, lets figure out how to use a server to open the web socket connection and store all output in a mysql database. But this was a bit harder then I expected... I tried node.js to run the javascript from my html file on my web server. that doesn't work.
It throws an error:
WebSocketRails.Event = (function() {
^
ReferenceError: WebSocketRails is not defined
at Object.<anonymous> (/Users/user/Desktop/tmp/wsBrowserClient.js:242:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
As far as I understand it now, the big difference between running js in the browser and in node.js is having or not having a DOM. The browser assigns variables to the window object but node.js can't do this.
So I have to change the javascript code to "node.js" javascript but can't find out where I have to start. My best guess would be with line
this.WebSocketRails = (function() {
but to what should I change it? Hope someone can give me a hand. If someone can tell my how to subscribe to a channel with a "normal" webwocket and then use a web socket client written for node js, of course that would also be fine.
Or a way to 'just' run the code as it is now server-side with another method, that would also help.
To be clear I'm a noob at javascript. Do know a thing or two about php, but that don't help me much here...
BIG thanks for any help!

Related

Mouse scroll key not working in Chrome & Firefox on website

Check this website - https://www.eviltech.in/
The mouse scroll key is not working in Google Chrome & Mozilla Firefox but it's working fine in Microsoft Edge.
My webpage won't scroll down
As suggested above the scroll key might not work if the CSS has overflow:hidden to body or html but that's not the case here. The scrollbar is visible in all browsers and the website can be scrolled by dragging the scrollbar.
Is there any other case where this might happen? What is the solution for that?
UPDATE:
The problem has been found in a javascript file wow.js by #ChrisHappy
I can't remove the entire wow.js from the website as it performs crucial animations required on the website.
Here are the wow.js codes:
(function() {
var MutationObserver, Util, WeakMap, __bind = function(fn, me) {
return function() {
return fn.apply(me, arguments)
}
},
__indexOf = [].indexOf || function(item) {
for (var i = 0, l = this.length; i < l; i++) {
if (i in this && this[i] === item) return i
}
return -1
};
Util = (function() {
function Util() {}
Util.prototype.extend = function(custom, defaults) {
var key, value;
for (key in custom) {
value = custom[key];
if (value != null) {
defaults[key] = value
}
}
return defaults
};
Util.prototype.isMobile = function(agent) {
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(agent)
};
return Util
})();
WeakMap = this.WeakMap || this.MozWeakMap || (WeakMap = (function() {
function WeakMap() {
this.keys = [];
this.values = []
}
WeakMap.prototype.get = function(key) {
var i, item, _i, _len, _ref;
_ref = this.keys;
for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
item = _ref[i];
if (item === key) {
return this.values[i]
}
}
};
WeakMap.prototype.set = function(key, value) {
var i, item, _i, _len, _ref;
_ref = this.keys;
for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
item = _ref[i];
if (item === key) {
this.values[i] = value;
return
}
}
this.keys.push(key);
return this.values.push(value)
};
return WeakMap
})());
MutationObserver = this.MutationObserver || this.WebkitMutationObserver || this.MozMutationObserver || (MutationObserver = (function() {
function MutationObserver() {
console.warn('MutationObserver is not supported by your browser.');
console.warn('WOW.js cannot detect dom mutations, please call .sync() after loading new content.')
}
MutationObserver.notSupported = !0;
MutationObserver.prototype.observe = function() {};
return MutationObserver
})());
this.WOW = (function() {
WOW.prototype.defaults = {
boxClass: 'wow',
animateClass: 'animated',
offset: 0,
mobile: !0,
live: !0
};
function WOW(options) {
if (options == null) {
options = {}
}
this.scrollCallback = __bind(this.scrollCallback, this);
this.scrollHandler = __bind(this.scrollHandler, this);
this.start = __bind(this.start, this);
this.scrolled = !0;
this.config = this.util().extend(options, this.defaults);
this.animationNameCache = new WeakMap()
}
WOW.prototype.init = function() {
var _ref;
this.element = window.document.documentElement;
if ((_ref = document.readyState) === "interactive" || _ref === "complete") {
this.start()
} else {
document.addEventListener('DOMContentLoaded', this.start)
}
return this.finished = []
};
WOW.prototype.start = function() {
var box, _i, _len, _ref;
this.stopped = !1;
this.boxes = this.element.getElementsByClassName(this.config.boxClass);
this.all = (function() {
var _i, _len, _ref, _results;
_ref = this.boxes;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
box = _ref[_i];
_results.push(box)
}
return _results
}).call(this);
if (this.boxes.length) {
if (this.disabled()) {
this.resetStyle()
} else {
_ref = this.boxes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
box = _ref[_i];
this.applyStyle(box, !0)
}
window.addEventListener('scroll', this.scrollHandler, !1);
window.addEventListener('resize', this.scrollHandler, !1);
this.interval = setInterval(this.scrollCallback, 50)
}
}
if (this.config.live) {
return new MutationObserver((function(_this) {
return function(records) {
var node, record, _j, _len1, _results;
_results = [];
for (_j = 0, _len1 = records.length; _j < _len1; _j++) {
record = records[_j];
_results.push((function() {
var _k, _len2, _ref1, _results1;
_ref1 = record.addedNodes || [];
_results1 = [];
for (_k = 0, _len2 = _ref1.length; _k < _len2; _k++) {
node = _ref1[_k];
_results1.push(this.doSync(node))
}
return _results1
}).call(_this))
}
return _results
}
})(this)).observe(document.body, {
childList: !0,
subtree: !0
})
}
};
WOW.prototype.stop = function() {
this.stopped = !0;
window.removeEventListener('scroll', this.scrollHandler, !1);
window.removeEventListener('resize', this.scrollHandler, !1);
if (this.interval != null) {
return clearInterval(this.interval)
}
};
WOW.prototype.sync = function(element) {
if (MutationObserver.notSupported) {
return this.doSync(this.element)
}
};
WOW.prototype.doSync = function(element) {
var box, _i, _len, _ref, _results;
if (!this.stopped) {
element || (element = this.element);
element = element.parentNode || element;
_ref = element.getElementsByClassName(this.config.boxClass);
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
box = _ref[_i];
if (__indexOf.call(this.all, box) < 0) {
this.applyStyle(box, !0);
this.boxes.push(box);
this.all.push(box);
_results.push(this.scrolled = !0)
} else {
_results.push(void 0)
}
}
return _results
}
};
WOW.prototype.show = function(box) {
this.applyStyle(box);
return box.className = "" + box.className + " " + this.config.animateClass
};
WOW.prototype.applyStyle = function(box, hidden) {
var delay, duration, iteration;
duration = box.getAttribute('data-wow-duration');
delay = box.getAttribute('data-wow-delay');
iteration = box.getAttribute('data-wow-iteration');
return this.animate((function(_this) {
return function() {
return _this.customStyle(box, hidden, duration, delay, iteration)
}
})(this))
};
WOW.prototype.animate = (function() {
if ('requestAnimationFrame' in window) {
return function(callback) {
return window.requestAnimationFrame(callback)
}
} else {
return function(callback) {
return callback()
}
}
})();
WOW.prototype.resetStyle = function() {
var box, _i, _len, _ref, _results;
_ref = this.boxes;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
box = _ref[_i];
_results.push(box.setAttribute('style', 'visibility: visible;'))
}
return _results
};
WOW.prototype.customStyle = function(box, hidden, duration, delay, iteration) {
if (hidden) {
this.cacheAnimationName(box)
}
box.style.visibility = hidden ? 'hidden' : 'visible';
if (duration) {
this.vendorSet(box.style, {
animationDuration: duration
})
}
if (delay) {
this.vendorSet(box.style, {
animationDelay: delay
})
}
if (iteration) {
this.vendorSet(box.style, {
animationIterationCount: iteration
})
}
this.vendorSet(box.style, {
animationName: hidden ? 'none' : this.cachedAnimationName(box)
});
return box
};
WOW.prototype.vendors = ["moz", "webkit"];
WOW.prototype.vendorSet = function(elem, properties) {
var name, value, vendor, _results;
_results = [];
for (name in properties) {
value = properties[name];
elem["" + name] = value;
_results.push((function() {
var _i, _len, _ref, _results1;
_ref = this.vendors;
_results1 = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
vendor = _ref[_i];
_results1.push(elem["" + vendor + (name.charAt(0).toUpperCase()) + (name.substr(1))] = value)
}
return _results1
}).call(this))
}
return _results
};
WOW.prototype.vendorCSS = function(elem, property) {
var result, style, vendor, _i, _len, _ref;
style = window.getComputedStyle(elem);
result = style.getPropertyCSSValue(property);
_ref = this.vendors;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
vendor = _ref[_i];
result = result || style.getPropertyCSSValue("-" + vendor + "-" + property)
}
return result
};
WOW.prototype.animationName = function(box) {
var animationName;
try {
animationName = this.vendorCSS(box, 'animation-name').cssText
} catch (_error) {
animationName = window.getComputedStyle(box).getPropertyValue('animation-name')
}
if (animationName === 'none') {
return ''
} else {
return animationName
}
};
WOW.prototype.cacheAnimationName = function(box) {
return this.animationNameCache.set(box, this.animationName(box))
};
WOW.prototype.cachedAnimationName = function(box) {
return this.animationNameCache.get(box)
};
WOW.prototype.scrollHandler = function() {
return this.scrolled = !0
};
WOW.prototype.scrollCallback = function() {
var box;
if (this.scrolled) {
this.scrolled = !1;
this.boxes = (function() {
var _i, _len, _ref, _results;
_ref = this.boxes;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
box = _ref[_i];
if (!(box)) {
continue
}
if (this.isVisible(box)) {
this.show(box);
continue
}
_results.push(box)
}
return _results
}).call(this);
if (!(this.boxes.length || this.config.live)) {
return this.stop()
}
}
};
WOW.prototype.offsetTop = function(element) {
var top;
while (element.offsetTop === void 0) {
element = element.parentNode
}
top = element.offsetTop;
while (element = element.offsetParent) {
top += element.offsetTop
}
return top
};
WOW.prototype.isVisible = function(box) {
var bottom, offset, top, viewBottom, viewTop;
offset = box.getAttribute('data-wow-offset') || this.config.offset;
viewTop = window.pageYOffset;
viewBottom = viewTop + this.element.clientHeight - offset;
top = this.offsetTop(box);
bottom = top + box.clientHeight;
return top <= viewBottom && bottom >= viewTop
};
WOW.prototype.util = function() {
return this._util || (this._util = new Util())
};
WOW.prototype.disabled = function() {
return !this.config.mobile && this.util().isMobile(navigator.userAgent)
};
return WOW
})()
}).call(this)
Is it possible to remove the lines of codes which are affecting the scrolling without affecting other functionalities here?
UPDATE 2: I tried removing entire wow.js but still the scrolling was not fixed and lots of vital functions stopped working.
That means the issue is not with the wow.js file.
Is there anything else that might be causing this issue?
There was problem in the JS file rd-smoothscroll.min.js
Removing the entire JS files has solved the problem.
! function(t, i, o) {
"use strict";
var e = "ontouchstart" in t,
r = ("undefined" != typeof InstallTrigger, "webkitTransform" in i.documentElement.style);
t.requestAnimFrame = function() {
return t.requestAnimationFrame || t.webkitRequestAnimationFrame || t.mozRequestAnimationFrame || t.oRequestAnimationFrame || t.msRequestAnimationFrame || function(i) {
t.setTimeout(i, 1e3 / 60)
}
}(), t.RDSmoothScroll = function() {
this.options = RDSmoothScroll.Defaults, this.animators = [], this.initialize()
}, RDSmoothScroll.Defaults = {
friction: .95,
step: 2,
minDistance: .1
}, RDSmoothScroll.Animator = function(t) {
var i = "html" === t.nodeName.toLowerCase() && r ? t.children[t.children.length - 1] : t;
this.target = t, this.originalTarget = i, this.direction = o, this.currentY = i.scrollTop, this.targetY = i.scrollTop, this.lastY = i.scrollTop, this.delta = 0, this.minY = 0, this.maxY = o, this.isPlaying = !1, this.speed = 0
}, RDSmoothScroll.Animator.prototype.update = function(i) {
var o = t.RDSmoothScroll.instance,
e = i.detail ? -1 * i.detail : i.wheelDelta / 40,
r = 0 > e ? -1 : 1;
r != this.direction && (this.speed = 0, this.direction = r), this.currentY = -this.originalTarget.scrollTop, this.delta = e, this.targetY += e, this.speed += (this.targetY - this.lastY) * o.options.step, this.lastY = this.targetY, this.start()
}, RDSmoothScroll.Animator.prototype.start = function() {
this.isPlaying || (this.isPlaying = !0, t.jQuery && t.jQuery(this.originalTarget).stop(), this.play())
}, RDSmoothScroll.Animator.prototype.play = function() {
var t = this;
this.isPlaying && (requestAnimFrame(function() {
t.play()
}), this.render())
}, RDSmoothScroll.Animator.prototype.stop = function() {
this.isPlaying && (this.speed = 0, this.isPlaying = !1)
}, RDSmoothScroll.Animator.prototype.render = function() {
var i = t.RDSmoothScroll.instance;
Math.abs(this.originalTarget.scrollTop - -this.currentY) > Math.abs(this.delta) && Math.abs(this.originalTarget.scrollTop - -this.currentY) > 1 && this.stop(), this.speed < -i.options.minDistance || this.speed > i.options.minDistance ? (this.currentY = this.currentY + this.speed, this.currentY > this.minY ? this.currentY = this.speed = 0 : this.currentY < this.maxY && (this.speed = 0, this.currentY = this.maxY), this.originalTarget.scrollTop = -this.currentY, this.speed *= i.options.friction) : this.stop()
}, RDSmoothScroll.prototype.initialize = function() {
t.addEventListener("mousewheel", this.onWheel), t.addEventListener("DOMMouseScroll", this.onWheel)
}, RDSmoothScroll.prototype.onWheel = function(i) {
if (!i.ctrlKey) {
var o, e, r = t.RDSmoothScroll.instance;
for (i.preventDefault(), o = i.target; null !== o && "html" != o.nodeName.toLocaleLowerCase() && !(("auto" == t.getComputedStyle(o).getPropertyValue("overflow") || "scroll" == t.getComputedStyle(o).getPropertyValue("overflow")) && o.scrollHeight > o.clientHeight && o.clientHeight > 0);) o = o.parentNode;
if (null != o) {
e = r.isAnimator(o) ? r.getAnimator(o) : r.createAnimator(o);
for (var n in r.animators) r.animators[n] !== e && r.animators[n].stop && r.animators[n].stop();
e.update(i)
}
}
}, RDSmoothScroll.prototype.createAnimator = function(t) {
return this.animators[this.animators.push(new RDSmoothScroll.Animator(t)) - 1]
}, RDSmoothScroll.prototype.isAnimator = function(t) {
for (var i in this.animators)
if (this.animators[i].target === t) return !0;
return !1
}, RDSmoothScroll.prototype.getAnimator = function(t) {
for (var i in this.animators)
if (this.animators[i].target === t) return this.animators[i];
return o
}, e || (t.RDSmoothScroll.instance = new RDSmoothScroll)
}(window, document)
Tested in:
Google Chrome
Firefox
Safari
All of those browsers mentioned above work fine.

Controller isn't counted as a function

I have many different controllers throughout this project and all of them are declared the same way. This one now isn't getting called/giving an error and I have no clue why. I've looked through it and it all looks right to me.
I think it's probably some syntax error I'm not seeing. If its something else please tell me. I'm trying to learn angular and everything helps. Also if you need anything else just tell me.
I've made sure its not that the app.js name got changed and been looking for missing syntax but can't find anything.
https://docs.angularjs.org/error/ng/areq?p0=companyDepartmentController&p1=not%20a%20function,%20got%20undefined
company-department-controller.js
app.controller('companyDepartmentController', ['$scope', '$timeout', 'companyService', function ($scope, $timeout, companyService) {
/**
* Create/Manage Company Departments & Shifts
*
*/
// INITIALIZE VARIABLES *********************************************************************************
var vm = this;
vm.Departments = [];
vm.activeDepartment = {}
vm.departmentBeforeEdit = {};
vm.activeShift = {};
vm.OffsetString = "";
vm.SaveDepartmentSuccessMessage = null;
vm.SaveDepartmentErrorMessage = null;
// STARTUP **********************************************************************************************
(vm.GetDepartments = function () {
companyService.GetDepartmentsWithShiftInformation().success(function (data) {
console.log('hi');
for (i = 0; i < data.length; i++) {
console.log(data[i])
}
vm.Departments = data;
// for now we are limiting this to 1
vm.activeDepartment = vm.Departments[0];
vm.setTimeZoneOffsets(vm.activeDepartment);
});
})();
// move to global location? handle this better?
(vm.findLocalOffsetString = function () {
console.log('hi1');
vm.OffsetString = moment(new Date()).format('ZZ');
})();
// $BROADCAST/$ON EVENTS ********************************************************************************
// EVENTS ***********************************************************************************************
vm.saveDepartment = function (department) {
// new
if (department.DepartmentID === 0 || typeof department.DepartmentID === 'undefined') {
}
// update
else {
companyService.UpdateDepartmentHeader(department).success(function (data) {
vm.SaveDepartmentSuccessMessage = "Saved!";
resetDepartmentMessage();
department.InEdit = false
});
}
};
vm.editDepartment = function (department) {
vm.activeDepartment = department;
vm.departmentBeforeEdit = angular.copy(vm.activeDepartment);
vm.activeDepartment.InEdit = true;
};
vm.cancelDepartmentEdit = function (department) {
for (var i = 0; i < vm.Departments.length; i++) {
if (department.DepartmentID === vm.Departments[i].DepartmentID) {
vm.Departments[i] = vm.departmentBeforeEdit;
vm.departmentBeforeEdit = {};
vm.activeDepartment = vm.Departments[i];
break;
};
};
};
vm.addShift = function () {
if (!vm.activeDepartment) return;
vm.activeShift = {
DepartmentID: vm.activeDepartment.DepartmentID,
StartTime: new Date(),
LocalStartTime: new Date(new Date() + vm.OffsetString)
};
vm.activeShift.StartTime.setSeconds(0);
vm.activeShift.LocalStartTime.setSeconds(0);
};
vm.deleteShift = function (shift) {
if (!shift) return;
if (confirm("Are you sure you want to delete the shift: " + shift.Name + "?")) {
companyService.DeleteShift(shift).success(function () {
angular.forEach(vm.activeDepartment.Shifts, function (c, i) {
if (c.ShiftID === shift.ShiftID) {
vm.activeDepartment.Shifts.splice(i, 1);
};
});
});
};
};
vm.setTimeZoneOffsets = function (department) {
if (!department || !department.Shifts || department.Shifts.length === 0) return;
for (var i = 0; i < department.Shifts.length; i++) {
department.Shifts[i].LocalStartTime = new Date(department.Shifts[i].StartTime + vm.OffsetString);
department.Shifts[i].EndTime = moment(department.Shifts[i].StartTime).add(department.Shifts[i].Duration, 'hours').toDate()
};
};
var fixTimezoneOnSave = function (shift) {
shift.StartTime = new Date(shift.LocalStartTime).toLocaleString();
};
vm.setActiveShift = function (shift) {
if (!shift) return;
vm.activeShift = angular.copy(shift);
};
vm.saveShift = function (shift) {
fixTimezoneOnSave(shift);
// new shift
if (shift.ShiftID === 0 || typeof shift.ShiftID === 'undefined') {
companyService.AddShift(shift).success(function (data) {
shift.ShiftID = data;
vm.SaveDepartmentSuccessMessage = "Saved!";
resetDepartmentMessage();
getUpdatedShiftsAndInfo();
}).error(function (e) {
vm.SaveDepartmentErrorMessage = e.error;
resetDepartmentMessage();
});
}
// updating existing
else {
companyService.UpdateShift(shift).success(function (data) {
vm.SaveDepartmentSuccessMessage = "Saved!";
resetDepartmentMessage();
getUpdatedShiftsAndInfo();
}).error(function (e) {
vm.SaveDepartmentErrorMessage = e.error;
resetDepartmentMessage();
});
}
}
var getUpdatedShiftsAndInfo = function () {
companyService.DepartmentAndShiftInformation(vm.activeDepartment.DepartmentID).success(function (data) {
vm.activeDepartment.DepartmentShiftInformation = data.DepartmentShiftInformation;
vm.activeDepartment.Shifts = data.Shifts;
vm.setTimeZoneOffsets(vm.activeDepartment);
});
};
var resetDepartmentMessage = function () {
// clear error/success message if they have values still
if (vm.SaveDepartmentSuccessMessage != null) {
$timeout(function () { vm.SaveDepartmentSuccessMessage = null; }, 2000);
}
if (vm.SaveDepartmentErrorMessage != null) {
$timeout(function () { vm.SaveDepartmentErrorMessage = null; }, 2000);
}
};
// create controller object in console if we have logging turned on
if (spectrum.LoggingEnabled) {
spectrum.logController(vm);
};
}]);
_CompanyDepartment.cshtml
<div class="container-fluid" data-ng-controller="companyDepartmentController as cd">
</div>
#section scripts {
#Scripts.Render("~/bundles/companyDepartments")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/angularjs")
}
app.js
var app = angular.module('app', ['angularFileUpload', 'ngSanitize', 'ui.mask', 'ui.select', 'ui.bootstrap', 'ui.bootstrap.tpls', 'angular.filter', 'smart-table', 'colorpicker.module'])
.config(function ($httpProvider) {
//make delete type json to facilitate passing object
//to our generic method.
$httpProvider.defaults.headers["delete"] = {
'Content-Type': 'application/json;charset=utf-8'
};
});
Outside of a naming issue with the controller(which I can't see), I would imagine your issue dealing with the company-department-controller.js not being loaded.
In setting up your angular project, I would suggest that you follow this angular styleguide. It has been very helpful to me in creating a well structured project.

ASP.NET referencing a javascript function

I have an ASP.NET page, written in VB.NET, that I'm trying to use javascript on. The script takes the value from one listbox and inserts it into another list box. I'm using a master page, which I'm pretty sure is the issue.
Here's the javascript:
function OT_transferLeft() { moveSelectedOptions(this.right, this.left, this.autoSort, this.staticOptionRegex); this.update(); }
function OT_transferRight() { moveSelectedOptions(this.left, this.right, this.autoSort, this.staticOptionRegex); this.update(); }
function OT_transferAllLeft() { moveAllOptions(this.right, this.left, this.autoSort, this.staticOptionRegex); this.update(); }
function OT_transferAllRight() { moveAllOptions(this.left, this.right, this.autoSort, this.staticOptionRegex); this.update(); }
function OT_saveRemovedLeftOptions(f) { this.removedLeftField = f; }
function OT_saveRemovedRightOptions(f) { this.removedRightField = f; }
function OT_saveAddedLeftOptions(f) { this.addedLeftField = f; }
function OT_saveAddedRightOptions(f) { this.addedRightField = f; }
function OT_saveNewLeftOptions(f) { this.newLeftField = f; }
function OT_saveNewRightOptions(f) { this.newRightField = f; }
function OT_update() {
var removedLeft = new Object();
var removedRight = new Object();
var addedLeft = new Object();
var addedRight = new Object();
var newLeft = new Object();
var newRight = new Object();
for (var i = 0; i < this.left.options.length; i++) {
var o = this.left.options[i];
newLeft[o.value] = 1;
if (typeof (this.originalLeftValues[o.value]) == "undefined") {
addedLeft[o.value] = 1;
removedRight[o.value] = 1;
}
}
for (var i = 0; i < this.right.options.length; i++) {
var o = this.right.options[i];
newRight[o.value] = 1;
if (typeof (this.originalRightValues[o.value]) == "undefined") {
addedRight[o.value] = 1;
removedLeft[o.value] = 1;
}
}
if (this.removedLeftField != null) { this.removedLeftField.value = OT_join(removedLeft, this.delimiter); }
if (this.removedRightField != null) { this.removedRightField.value = OT_join(removedRight, this.delimiter); }
if (this.addedLeftField != null) { this.addedLeftField.value = OT_join(addedLeft, this.delimiter); }
if (this.addedRightField != null) { this.addedRightField.value = OT_join(addedRight, this.delimiter); }
if (this.newLeftField != null) { this.newLeftField.value = OT_join(newLeft, this.delimiter); }
if (this.newRightField != null) { this.newRightField.value = OT_join(newRight, this.delimiter); }
}
function OT_join(o, delimiter) {
var val; var str = "";
for (val in o) {
if (str.length > 0) { str = str + delimiter; }
str = str + val;
}
return str;
}
function OT_setDelimiter(val) { this.delimiter = val; }
function OT_setAutoSort(val) { this.autoSort = val; }
function OT_setStaticOptionRegex(val) { this.staticOptionRegex = val; }
function OT_init(theform) {
this.form = theform;
if (!theform[this.left]) { alert("OptionTransfer init(): Left select list does not exist in form!"); return false; }
if (!theform[this.right]) { alert("OptionTransfer init(): Right select list does not exist in form!"); return false; }
this.left = theform[this.left];
this.right = theform[this.right];
for (var i = 0; i < this.left.options.length; i++) {
this.originalLeftValues[this.left.options[i].value] = 1;
}
for (var i = 0; i < this.right.options.length; i++) {
this.originalRightValues[this.right.options[i].value] = 1;
}
if (this.removedLeftField != null) { this.removedLeftField = theform[this.removedLeftField]; }
if (this.removedRightField != null) { this.removedRightField = theform[this.removedRightField]; }
if (this.addedLeftField != null) { this.addedLeftField = theform[this.addedLeftField]; }
if (this.addedRightField != null) { this.addedRightField = theform[this.addedRightField]; }
if (this.newLeftField != null) { this.newLeftField = theform[this.newLeftField]; }
if (this.newRightField != null) { this.newRightField = theform[this.newRightField]; }
this.update();
}
// -------------------------------------------------------------------
// OptionTransfer()
// This is the object interface.
// -------------------------------------------------------------------
function OptionTransfer(l, r) {
this.form = null;
this.left = l;
this.right = r;
this.autoSort = true;
this.delimiter = ",";
this.staticOptionRegex = "";
this.originalLeftValues = new Object();
this.originalRightValues = new Object();
this.removedLeftField = null;
this.removedRightField = null;
this.addedLeftField = null;
this.addedRightField = null;
this.newLeftField = null;
this.newRightField = null;
this.transferLeft = OT_transferLeft;
this.transferRight = OT_transferRight;
this.transferAllLeft = OT_transferAllLeft;
this.transferAllRight = OT_transferAllRight;
this.saveRemovedLeftOptions = OT_saveRemovedLeftOptions;
this.saveRemovedRightOptions = OT_saveRemovedRightOptions;
this.saveAddedLeftOptions = OT_saveAddedLeftOptions;
this.saveAddedRightOptions = OT_saveAddedRightOptions;
this.saveNewLeftOptions = OT_saveNewLeftOptions;
this.saveNewRightOptions = OT_saveNewRightOptions;
this.setDelimiter = OT_setDelimiter;
this.setAutoSort = OT_setAutoSort;
this.setStaticOptionRegex = OT_setStaticOptionRegex;
this.init = OT_init;
this.update = OT_update;
}
var lb1 = document.getElementById("<%=lbSiteType.ClientID%>");
var lb2 = document.getElementById("<%=lbSelectedSiteType.ClientID%>");
var opt = new OptionTransfer(lb1, lb2);
alert(opt);
opt.setAutoSort(true);
opt.setDelimiter(",");
opt.setStaticOptionRegex("^(Bill|Bob|Matt)$");
opt.saveRemovedLeftOptions("removedLeft");
opt.saveRemovedRightOptions("removedRight");
opt.saveAddedLeftOptions("addedLeft");
opt.saveAddedRightOptions("addedRight");
opt.saveNewLeftOptions("newLeft");
opt.saveNewRightOptions("newRight");
and here's the code from the control:
<asp:Button ID="btnMoveAll" Text=" >> " CssClass="button7" CausesValidation="false"
ONCLICK="opt.transferRight()"
runat="server" /><br />
In short, it doesn't work. I keep getting an 'opt' is not a member of the page. Can someone explain how I can properly call this code?
To invoke client Methods(javascript) use OnClientClick
<asp:Button ID="btnMoveAll" Text="" CssClass="button7" CausesValidation="false"
OnClientClick="opt.transferRight()"
runat="server" />

bootstrap popover by hover in image picker

I'm trying to put Popover and Image Picker together.
The image picker function turn select in html into image and allow users to select.
The problem is that I dont have the code of image in html so I cannot add the popover thing in it.
How do I change javascript of the image picker so that when users hover over the div or the image, bootstrap popover will show? And when I leave the div / image, the popover will disappear.
I have over 10 image and each of them have different text.
The code of image is created by the function, but i do not understand the code in the function
JavaScript of Image Picker:
(function() {
var ImagePicker, ImagePickerOption, both_array_are_equal, sanitized_options,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
jQuery.fn.extend({
imagepicker: function(opts) {
if (opts == null) {
opts = {};
}
return this.each(function() {
var select;
select = jQuery(this);
if (select.data("picker")) {
select.data("picker").destroy();
}
select.data("picker", new ImagePicker(this, sanitized_options(opts)));
if (opts.initialized != null) {
return opts.initialized.call(select.data("picker"));
}
});
}
});
sanitized_options = function(opts) {
var default_options;
default_options = {
hide_select: true,
show_label: false,
initialized: void 0,
changed: void 0,
clicked: void 0,
selected: void 0,
limit: void 0,
limit_reached: void 0
};
return jQuery.extend(default_options, opts);
};
both_array_are_equal = function(a, b) {
return jQuery(a).not(b).length === 0 && jQuery(b).not(a).length === 0;
};
ImagePicker = (function() {
function ImagePicker(select_element, opts) {
this.opts = opts != null ? opts : {};
this.sync_picker_with_select = __bind(this.sync_picker_with_select, this);
this.select = jQuery(select_element);
this.multiple = this.select.attr("multiple") === "multiple";
if (this.select.data("limit") != null) {
this.opts.limit = parseInt(this.select.data("limit"));
}
this.build_and_append_picker();
}
ImagePicker.prototype.destroy = function() {
var option, _i, _len, _ref;
_ref = this.picker_options;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
option = _ref[_i];
option.destroy();
}
this.picker.remove();
this.select.unbind("change");
this.select.removeData("picker");
return this.select.show();
};
ImagePicker.prototype.build_and_append_picker = function() {
var _this = this;
if (this.opts.hide_select) {
this.select.hide();
}
this.select.change(function() {
return _this.sync_picker_with_select();
});
if (this.picker != null) {
this.picker.remove();
}
this.create_picker();
this.select.after(this.picker);
return this.sync_picker_with_select();
};
ImagePicker.prototype.sync_picker_with_select = function() {
var option, _i, _len, _ref, _results;
_ref = this.picker_options;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
option = _ref[_i];
if (option.is_selected()) {
_results.push(option.mark_as_selected());
} else {
_results.push(option.unmark_as_selected());
}
}
return _results;
};
ImagePicker.prototype.create_picker = function() {
this.picker = jQuery("<ul class='thumbnails image_picker_selector'></ul>");
this.picker_options = [];
this.recursively_parse_option_groups(this.select, this.picker);
return this.picker;
};
ImagePicker.prototype.recursively_parse_option_groups = function(scoped_dom, target_container) {
var container, option, option_group, _i, _j, _len, _len1, _ref, _ref1, _results;
_ref = scoped_dom.children("optgroup");
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
option_group = _ref[_i];
option_group = jQuery(option_group);
container = jQuery("<ul></ul>");
container.append(jQuery("<li class='group_title'>" + (option_group.attr("label")) + "</li>"));
target_container.append(jQuery("<li>").append(container));
this.recursively_parse_option_groups(option_group, container);
}
_ref1 = (function() {
var _k, _len1, _ref1, _results1;
_ref1 = scoped_dom.children("option");
_results1 = [];
for (_k = 0, _len1 = _ref1.length; _k < _len1; _k++) {
option = _ref1[_k];
_results1.push(new ImagePickerOption(option, this, this.opts));
}
return _results1;
}).call(this);
_results = [];
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
option = _ref1[_j];
this.picker_options.push(option);
if (!option.has_image()) {
continue;
}
_results.push(target_container.append(option.node));
}
return _results;
};
ImagePicker.prototype.has_implicit_blanks = function() {
var option;
return ((function() {
var _i, _len, _ref, _results;
_ref = this.picker_options;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
option = _ref[_i];
if (option.is_blank() && !option.has_image()) {
_results.push(option);
}
}
return _results;
}).call(this)).length > 0;
};
ImagePicker.prototype.selected_values = function() {
if (this.multiple) {
return this.select.val() || [];
} else {
return [this.select.val()];
}
};
ImagePicker.prototype.toggle = function(imagepicker_option) {
var new_values, old_values, selected_value;
old_values = this.selected_values();
selected_value = imagepicker_option.value().toString();
if (this.multiple) {
if (__indexOf.call(this.selected_values(), selected_value) >= 0) {
new_values = this.selected_values();
new_values.splice(jQuery.inArray(selected_value, old_values), 1);
this.select.val([]);
this.select.val(new_values);
} else {
if ((this.opts.limit != null) && this.selected_values().length >= this.opts.limit) {
if (this.opts.limit_reached != null) {
this.opts.limit_reached.call(this.select);
}
} else {
this.select.val(this.selected_values().concat(selected_value));
}
}
} else {
if (this.has_implicit_blanks() && imagepicker_option.is_selected()) {
this.select.val("");
} else {
this.select.val(selected_value);
}
}
if (!both_array_are_equal(old_values, this.selected_values())) {
this.select.change();
if (this.opts.changed != null) {
return this.opts.changed.call(this.select, old_values, this.selected_values());
}
}
};
return ImagePicker;
})();
ImagePickerOption = (function() {
function ImagePickerOption(option_element, picker, opts) {
this.picker = picker;
this.opts = opts != null ? opts : {};
this.clicked = __bind(this.clicked, this);
this.option = jQuery(option_element);
this.create_node();
}
ImagePickerOption.prototype.destroy = function() {
return this.node.find(".thumbnail").unbind();
};
ImagePickerOption.prototype.has_image = function() {
return this.option.data("img-src") != null;
};
ImagePickerOption.prototype.is_blank = function() {
return !((this.value() != null) && this.value() !== "");
};
ImagePickerOption.prototype.is_selected = function() {
var select_value;
select_value = this.picker.select.val();
if (this.picker.multiple) {
return jQuery.inArray(this.value(), select_value) >= 0;
} else {
return this.value() === select_value;
}
};
ImagePickerOption.prototype.mark_as_selected = function() {
return this.node.find(".thumbnail").addClass("selected");
};
ImagePickerOption.prototype.unmark_as_selected = function() {
return this.node.find(".thumbnail").removeClass("selected");
};
ImagePickerOption.prototype.value = function() {
return this.option.val();
};
ImagePickerOption.prototype.label = function() {
if (this.option.data("img-label")) {
return this.option.data("img-label");
} else {
return this.option.text();
}
};
ImagePickerOption.prototype.clicked = function() {
this.picker.toggle(this);
if (this.opts.clicked != null) {
this.opts.clicked.call(this.picker.select, this);
}
if ((this.opts.selected != null) && this.is_selected()) {
return this.opts.selected.call(this.picker.select, this);
}
};
ImagePickerOption.prototype.create_node = function() {
var image, thumbnail;
this.node = jQuery("<li/>");
image = jQuery("<img class='image_picker_image'/>");
image.attr("src", this.option.data("img-src"));
thumbnail = jQuery("<div class='thumbnail'>");
thumbnail.click({
option: this
}, function(event) {
return event.data.option.clicked();
});
thumbnail.append(image);
if (this.opts.show_label) {
thumbnail.append(jQuery("<p/>").html(this.label()));
}
this.node.append(thumbnail);
return this.node;
};
return ImagePickerOption;
})();
}).call(this);
Thank you for your help!
I understand more what you are looking for. Unfortunately I think you are going to have to use javascript to apply the pop-over because this elements are added to the DOM dynamically.
With one line of code you can add an ID to each image:
...
ImagePickerOption.prototype.create_node = function() {
var image, thumbnail;
this.node = jQuery("<li/>");
image = jQuery("<img class='image_picker_image'/>");
image.attr("src", this.option.data("img-src"));
//**ADD THIS LINE**
image.attr("id", this.option.data("img-id"));
//*****************
thumbnail = jQuery("<div class='thumbnail'>");
thumbnail.click({
option: this
}, function(event) {
return event.data.option.clicked();
});
thumbnail.append(image);
if (this.opts.show_label) {
thumbnail.append(jQuery("<p/>").html(this.label()));
}
this.node.append(thumbnail);
return this.node;
};
...
In you options tag you can now do:
<option
data-img-src='http://www.example.com/image.jpg'
data-img-id='picture1'>
This will allow you do add the popover through javascript like so:
$('#picture1').popover({ content: 'Picture 1 Message' });
Important Note: Use the I imagepicker initialized callback method to apply your popovers, this will ensure your elements exist on the DOM.

Why is my ActionButton base-class being overwritten?

My "base class" does not seem to be populating correctly. Why?
<script type="text/javascript">
var exceptions = {
NotImplementedException: function (message) {
this.name = 'NotImplementedException';
this.message = message || 'Property or method is not implemented.';
}
};
exceptions.NotImplementedException.prototype = Error.prototype;
function ActionButton() {
this.execute = function () {
throw new exceptions.NotImplementedException("Execute is not implemented.");
};
this.render = function (data) {
throw new exceptions.NotImplementedException("Render is not implemented.");
};
this.$template = function () {
throw new exceptions.NotImplementedException("$template is not implemented.");
};
};
function ImageActionButton() {
this.image = { url: '' };
};
function TextActionButton() {
this.text = '';
};
function StandardActionButton() {
this.text = '';
this.image = { url: '' };
};
function MenuActionButton() {
this.buttons = [];
};
ImageActionButton.prototype = new ActionButton();
ImageActionButton.prototype.constructor = ImageActionButton;
TextActionButton.prototype = new ActionButton();
TextActionButton.prototype.constructor = TextActionButton;
StandardActionButton.prototype = new ActionButton();
StandardActionButton.prototype.constructor = StandardActionButton;
MenuActionButton.prototype = new ActionButton();
MenuActionButton.prototype.constructor = MenuActionButton;
// This fails
if (ImageActionButton.prototype != ActionButton) {
alert("ImageActionButton prototype is not ActionButton!");
}
// This works
if (ImageActionButton.prototype.constructor != ImageActionButton) {
alert("ImageActionButton prototype.constructor is not ImageActionButton!");
}
</script>
I think you'll want to use instanceof instead of comparing like you are.
if (ImageActionButton instanceof ActionButton) {
alert("ImageActionButton prototype is not ActionButton!");
}

Categories

Resources