Javascript Run prototype in another file - javascript

How can i Execute the Client.prototype.disconnect on another page of javascript code?
Maybe i just have to inherit it?
If yes, then how do i inherit it?
Thanks.
function(Komanda, _, Helpers, Channels, Channel, ChannelView, ChannelsView, Message, Notice, NamesView, Popup, moment, uuid) {
var Client = function(session) {
var self = this;
self.irc = window.requireNode("irc");
self.options = session.attributes;
self.options.stripColors = false;
self.nick = session.attributes.nick;
self.socket = null;
self.session = session;
self.retryCount = 300;
self.retryCountCurrent = 0;
self.retryFunction = null;
self.attemptingReconnect = false;
self.allowReconnect = true;
self.topics = {};
self.binded = false;
self.channels = new Channels();
self.channel = new Channel();
self.channelsView = new ChannelsView({
collection: self.channels,
model: self.channel
});
self.views = [];
$(".channel-item[data-name=\"Status\"]").removeClass("selected");
$(".channel").hide();
var c = new Channel({
channel: "Status",
topic: false,
names: {},
name: "Server Status",
server: self.options.uuid,
status: true,
pm: false
});
self.channels.add(c);
var view = new ChannelView({
model: c
});
Komanda.current = {
server: self.options.uuid,
channel: "Status"
};
$(".channel-holder").append(view.render().el);
var selector = $("#sidebar div.session[data-id=\"" + self.options.uuid + "\"]");
if (selector.find(".channel-list").length > 0) {
selector.find(".channel-list").replaceWith(self.channelsView.render().el);
} else {
selector.append(self.channelsView.render().el);
}
self._whois = {};
return this;
};
Client.prototype.disconnect = function(callback) {
var self = this;
self.attemptingReconnect = false;
self.socket.disconnect("quit message", function() {
self.session.set("connectionOpen", false);
self.clearViews();
self.socket.conn.end();
if (_.isFunction(callback)) {
callback(self);
}
});
};

Related

Creating a common file by combining two similar functions

I have two functions that are mostly similar in different files and I want to combine them into one file but as can be seen in the code, some product properties are different from each other and I want to handle this dynamically. What is the correct way to do this?
File-1:
function run(args) {
try {
var sitePreferences = require("sitePreferences");
var pinterestHelpers = require("~/cartridge/scripts/helpers/pinterestHelpers");
var maxRowLength = sitePreferences.get("pinterestProductFeedMaxRow");
var hostName = require("dw/system/Site").current.httpsHostName;
var products = pinterestHelpers.onBeforeStep(args);
var fileNumber = 1;
var lineCount = 1;
pinterestHelpers.removeFiles(args);
var csvObject = pinterestHelpers.createCsvFile(fileNumber, args);
var csv = csvObject.csv;
var fileCreationResponse;
var fileWriter = csvObject.fileWriter;
while (products.hasNext()) {
var currentProductObject = products.next();
var priceObject = pinterestHelpers.getPrice(currentProductObject);
var product = {};
if (pinterestHelpers.shouldBeExported(currentProductObject)) {
if (maxRowLength !== lineCount) {
product.id = pinterestHelpers.getId(currentProductObject);
product.title = pinterestHelpers.getTitle(currentProductObject);
product.description = pinterestHelpers.getDescription(currentProductObject);
product.link = pinterestHelpers.getLink(currentProductObject, hostName);
product.image_link = pinterestHelpers.getImageLink(currentProductObject);
product.price = priceObject && priceObject.list ? priceObject.list : "";
product.availability = pinterestHelpers.getAvailability(currentProductObject);
product.item_group_id = pinterestHelpers.getItemGroupID(currentProductObject);
product.additional_image_link = pinterestHelpers.getAdditionalImageLink(currentProductObject);
product.brand = pinterestHelpers.getBrand(currentProductObject);
product.google_product_category = pinterestHelpers.getGoogleCategoryByProduct(currentProductObject);
product.sale_price = priceObject && priceObject.sale ? priceObject.sale : "";
product.color = pinterestHelpers.getColor(currentProductObject);
product.age_group = pinterestHelpers.getCustomAttribute(currentProductObject, "age_group", "Adult");
product.gender = pinterestHelpers.getCustomAttribute(currentProductObject, "gender", "unisex");
product.condition = pinterestHelpers.getCustomAttribute(currentProductObject, "condition", "new");
product.variant_names = pinterestHelpers.getSize(currentProductObject);
product.variant_values = pinterestHelpers.getColor(currentProductObject);
product.product_type = pinterestHelpers.getProductType(currentProductObject);
product.material = pinterestHelpers.getCustomAttribute(currentProductObject, "material");
product.pattern = pinterestHelpers.getCustomAttribute(currentProductObject, "pattern");
product.shipping = pinterestHelpers.getShipping(currentProductObject, priceObject).group;
product.adult = pinterestHelpers.getCustomAttribute(currentProductObject, "adult", "FALSE");
csv.writeNext([
product.id,
product.title,
product.description,
product.link,
product.image_link,
product.price,
product.availability,
product.item_group_id,
product.variant_names,
product.variant_values,
product.additional_image_link,
product.brand,
product.product_type,
product.sale_price,
product.age_group,
product.color,
product.gender,
product.material,
product.pattern,
product.shipping,
product.adult,
product.condition,
product.google_product_category
]);
lineCount++;
} else {
fileNumber++;
lineCount = 1;
fileCreationResponse = pinterestHelpers.createCsvFile(fileNumber, args);
csv = fileCreationResponse.csv;
}
}
}
products.close();
csv.close();
fileWriter.close();
Logger.info("Pinterest feed exported at {0}", pinterestHelpers.getFeedURL(args, fileCreationResponse.fileName));
return new Status(Status.OK, 'OK', 'Export successful');
} catch (e) {
return new Status(Status.ERROR, 'ERROR', 'Failed to export the feed: ' + e);
}
}
exports.Run = run;
File-2:
function run(args) {
try {
var snapchatHelpers = require("~/cartridge/scripts/helpers/snapchatHelpers");
var maxRowLength = sitePreferences.get("snapchatProductFeedMaxRow");
var hostName = require("dw/system/Site").current.httpsHostName;
var products = snapchatHelpers.onBeforeStep(args);
var fileNumber = 1;
var lineCount = 1;
snapchatHelpers.removeFiles(args);
var csvObject = snapchatHelpers.createCsvFile(fileNumber, args);
var csv = csvObject.csv;
var fileCreationResponse;
var fileWriter = csvObject.fileWriter;
while (products.hasNext()) {
var currentProductObject = products.next();
var priceObject = snapchatHelpers.getPrice(currentProductObject);
var product = {};
if (snapchatHelpers.shouldBeExported(currentProductObject)) {
if (maxRowLength !== lineCount) {
//Required Product Metadata
product.id = snapchatHelpers.getId(currentProductObject);
product.title = snapchatHelpers.getTitle(currentProductObject);
product.description = snapchatHelpers.getDescription(currentProductObject);
product.link = snapchatHelpers.getLink(currentProductObject, hostName);
product.imageLink = snapchatHelpers.getImageLink(currentProductObject);
product.price = priceObject && priceObject.list ? priceObject.list : "";
product.availability = snapchatHelpers.getAvailability(currentProductObject);
product.item_group_id = snapchatHelpers.getItemGroupID(currentProductObject);
product.additional_image_link = snapchatHelpers.getAdditionalImageLink(currentProductObject);
product.brand = snapchatHelpers.getBrand(currentProductObject);
product.google_product_category = snapchatHelpers.getGoogleCategoryByProduct(currentProductObject);
product.sale_price = priceObject && priceObject.sale ? priceObject.sale : "";
product.color = snapchatHelpers.getColor(currentProductObject);
product.age_group = snapchatHelpers.getCustomAttribute(currentProductObject, "age_group", "Adult");
product.gender = snapchatHelpers.getCustomAttribute(currentProductObject, "gender", "Unisex");
product.condition = snapchatHelpers.getCustomAttribute(currentProductObject, "condition", "New");
//Optional Product Metadata
product.product_type = snapchatHelpers.getProductType(currentProductObject);
product.adult = snapchatHelpers.getCustomAttribute(currentProductObject, "adult", "No");
product.size = snapchatHelpers.getSize(currentProductObject);
product.sale_price_effective_date = priceObject && priceObject.startDate ? StringUtils.format("{0}/{1}", priceObject.startDate, priceObject.endDate) : "";
csv.writeNext([
product.id,
product.title,
product.description,
product.link,
product.imageLink,
product.availability,
product.price,
product.brand,
product.age_group,
product.color,
product.condition,
product.gender,
product.item_group_id,
product.google_product_category,
product.product_type,
product.adult,
product.size,
product.additional_image_link,
product.sale_price,
product.sale_price_effective_date
]);
lineCount++;
} else {
fileNumber++;
lineCount = 1;
fileCreationResponse = snapchatHelpers.createCsvFile(fileNumber, args);
csv = fileCreationResponse.csv;
}
}
}
products.close();
csv.close();
fileWriter.close();
Logger.info("Facebook feed exported at {0}", snapchatHelpers.getFeedURL(args, fileCreationResponse.fileName));
return new Status(Status.OK, 'OK', 'Export successful');
} catch (e) {
return new Status(Status.ERROR, 'ERROR', 'Failed to export the feed: ' + e);
}
}
exports.Run = run;
Using inheritance with an Object oriented structure seems logical at first, but since we are working with javascript, I would like to implement it if there is a simpler way by sacrificing object oriented.

Script work in a browser but not in NodeJS

I'm struggling trying to understand why this script works perfectly in the browser but not in Node.js in the server.
data = [{"stars": 3}, {"stars": 2}]
var ParseParameter = function(){
this.parser = "";
}
ParseParameter.prototype = {
setStrategy: function(parser) {
this.parser = parser;
},
parse: function(parameter) {
return this.parser.parse(parameter);
}
};
var IntegerParser = function(filter){
this.parameter = '';
this.filter = filter;
this.parse = function(parameter){
this.parameter = parseInt(parameter);
}
this.filterBy = function(item){
return item[this.filter] == this.parameter;
}
}
var filter = 'stars',
parameter = '2',
parseParameter = new ParseParameter();
var integerParser = new IntegerParser(filter);
parseParameter.setStrategy(integerParser);
parseParameter.parse(parameter);
var dataFiltered = data.filter(parseParameter.parser.filterBy);
console.log(dataFiltered);
At the server, I print in console the values of this.parameter and this.filter at the function filterBy and these are undefined
I'm running on Node.js version 8.11.2
Any advice will be appreciated.
The is may be due to problem of this keyword in your script. Inside an inner function this refers to window or global object. For example,
Inside the following code, this.filter of this.filterBy is not referring to the filter property that exists inside the scope of IntegerParser function instead it is referring the variable being defined as var filter = 'stars'. Change this name to something else and you'll see undefined and it won't work on browser as well. That's what could be your issue.
var IntegerParser = function(filter){
this.parameter = '';
this.filter = filter;
this.parse = function(parameter){
this.parameter = parseInt(parameter);
}
this.filterBy = function(item){
return item[this.filter] == this.parameter;
}
}
Instead of using this you could use a known solution for this problem by storing this to a variable for later usage. like in following example:
var IntegerParser = function(filter){
this.parameter = '';
this.filter = filter;
var self = this; // store this to self and use self in inner functions
this.parse = function(parameter){
self.parameter = parseInt(parameter);
}
this.filterBy = function(item){
return item[self.filter] == self.parameter;
}
}
Your entire code including my solution is as follow:
data = [{"stars": 3}, {"stars": 2}]
var ParseParameter = function(){
this.parser = "";
}
ParseParameter.prototype = {
setStrategy: function(parser) {
this.parser = parser;
},
parse: function(parameter) {
return this.parser.parse(parameter);
}
};
var IntegerParser = function(filter){
this.parameter = '';
this.filter = filter;
var self = this;
this.parse = function(parameter){
self.parameter = parseInt(parameter);
}
this.filterBy = function(item){
return item[self.filter] == self.parameter;
}
}
var filter = 'stars',
parameter = '2',
parseParameter = new ParseParameter();
var integerParser = new IntegerParser(filter);
parseParameter.setStrategy(integerParser);
parseParameter.parse(parameter);
var dataFiltered = data.filter(parseParameter.parser.filterBy);
console.log(dataFiltered);
It should work without any problem. Please try and see if it works for you.

Uncaught TypeError: Object #<AbstractAjaxReq> has no method 'getAjaxResponse'

I want to implement some good OOP practices into my javascript somehow. As you can see I am having an abstractAjaxRequest and then giving it some children that define its getAjaxResponse function. I get the error posted at the bottom, on this line: self.getAjaxResponse(). Anyone see the error of my ways?
function soapReq() {
var ajaxRequest = new SignInAjaxReq();
ajaxRequest.init();
var SOAPRequest = getSOAPHead();
var bodyArgs = getLoginAttempt();
SOAPRequest += getSOAPBody(bodyArgs[0], bodyArgs[1], bodyArgs[2]);
SOAPRequest += getSOAPFoot();
var url = 'xxx'
ajaxRequest.ajaxRequest.open('POST', url, true);
ajaxRequest.ajaxRequest.setRequestHeader( "Content-Type","text/xml; charset=utf-8");
ajaxRequest.ajaxRequest.send(SOAPRequest);
}
function AbstractAjaxReq() {
var self = this;
this.init = function() {
self.ajaxRequest = new XMLHttpRequest();
self.ajaxRequest.onreadystatechange = function() {
if(self.ajaxRequest.readyState === 4){
self.getAjaxResponse() // error here
}
};
return self.ajaxRequest;
};
};
function SignInAjaxReq() {
var self = this;
this.getAjaxResponse = function() {
var xml = self.ajaxRequest.responseXML;
var x=xml.getElementsByTagName("signInResult");
for (i=0;i<x.length;i++) {
console.log(x[i].childNodes[0].nodeValue);
}
};
};
SignInAjaxReq.prototype = new AbstractAjaxReq();
Uncaught TypeError: Object #<AbstractAjaxReq> has no method 'getAjaxResponse' SoapRequest.js:42
self.ajaxRequest.onreadystatechange
Your inheritance is flawed. When you create the prototype by new AbstractReq(), then the self closure variable will point to that prototype object - which does not have a getAjaxResponse method.
Fix #1: Use correct inheritance:
function AbstractAjaxReq() {
var self = this;
this.init = function() {
self.ajaxRequest = new XMLHttpRequest();
self.ajaxRequest.onreadystatechange = function() {
if(self.ajaxRequest.readyState === 4){
self.getAjaxResponse() // no more error here
}
};
return self.ajaxRequest;
};
};
function SignInAjaxReq() {
AbstractAjaxReq.call(this); // invoke the super constructor
var self = this;
this.getAjaxResponse = function() {
var xml = self.ajaxRequest.responseXML;
var x=xml.getElementsByTagName("signInResult");
for (i=0;i<x.length;i++) {
console.log(x[i].childNodes[0].nodeValue);
}
};
};
SignInAjaxReq.prototype = Object.create(AbstractAjaxReq.prototype);
Fix #2: Assign the actual instance to self by creating the variable in the init function:
function AbstractAjaxReq() {
this.init = function() {
var self = this; // here!
self.ajaxRequest = new XMLHttpRequest();
self.ajaxRequest.onreadystatechange = function() {
if(self.ajaxRequest.readyState === 4){
self.getAjaxResponse() // no more error here
}
};
return self.ajaxRequest;
};
};
Also, use the prototype! Example:
var abstractAjaxPrototype = {
init: function() {
var self = this; // here!
this.ajaxRequest = new XMLHttpRequest();
this.ajaxRequest.onreadystatechange = function() {
if (self.ajaxRequest.readyState === 4){
self.getAjaxResponse() // no more error here
}
};
return this.ajaxRequest;
}
};
function SignInAjaxReq() { }
SignInAjaxReq.prototype = Object.create(abstractAjaxPrototype);
SignInAjaxReq.prototype.getAjaxResponse = function() {
var xml = this.ajaxRequest.responseXML;
var x = xml.getElementsByTagName("signInResult");
for (i=0; i<x.length; i++) {
console.log(x[i].childNodes[0].nodeValue);
}
};
And: don't use init methods, use the constructor:
function AbstractAjaxReq() {
var self = this; // here!
self.ajaxRequest = new XMLHttpRequest();
self.ajaxRequest.onreadystatechange = function() {
if(self.ajaxRequest.readyState === 4){
self.getAjaxResponse() // no more error here
}
};
};
function SignInAjaxReq() {
AbstractAjaxReq.call(this); // invoke the super constructor
}
SignInAjaxReq.prototype = Object.create(abstractAjaxPrototype);
SignInAjaxReq.prototype.getAjaxResponse = function() {
var xml = this.ajaxRequest.responseXML;
var x = xml.getElementsByTagName("signInResult");
for (i=0; i<x.length; i++) {
console.log(x[i].childNodes[0].nodeValue);
}
};
// Usage:
var ajaxRequest = new SignInAjaxReq();
// no ajaxRequest.init()!

how can i add attribute foreach feature

My project is geographic maps application.
This is my protocol:
var myprotocol = new OpenLayers.Protocol.HTTP({
url: url,
format: new OpenLayers.Format.GeoJSON({
extractStyles: true,
extractAttributes: true
})
});
This is my layer function:
var layer = new OpenLayers.Layer.Vector("layerName", {
projection: epsg4326,
strategies: strategies,
protocol: myprotocol,
displayInLayerSwitcher: true
});
layer.events.register('loadend', layer, function (evt) {
console.log("onloadend was called");
});
layer.events.register('loadstart', layer, function (evt) {
console.log("onloadstart was called");
}
This is my other function:
myprotocol.read({
// maxFeatures: 100,
callback: function (resp) {
console.log("read _CallBack was called");
console.log(resp);
}
});
myprotocol.handleResponse = function (resp, opt) {
console.log("handleResponse was called");
};
These are my attributes:
var data = new Object();
data.iconUrl = katman.iconUrl;
data.fillColor = katman.fillColor;
data.fillOpacity = katman.fillOpacity;
data.graphicHeight = katman.graphicHeight;
data.graphicOpacity = katman.graphicOpacity;
data.graphicWidth = katman.graphicWidth;
data.graphicXOffset = katman.graphicXOffset;
data.graphicYOffset = katman.graphicYOffset;
data.pointRadius = katman.pointRadius;
data.pointerEvents = katman.pointerEvents;
data.rotation = katman.rotation;
data.strokeColor = katman.strokeColor;
data.strokeDashstyle = katman.strokeDashstyle;
data.strokeLinecap = katman.strokeLinecap;
data.strokeOpacity = katman.strokeOpacity;
data.strokeWidth = katman.strokeWidth;
data.layerId = feature.data.layerId;
data.shapeId = feature.data.shapeId;
I want to add this attributes for each feature that I received featurecollection object from web service.
I've solved this problem with the following code.thank you for help me..
myprotocol.handleResponse = function (resp, opt) {
console.log("handleResponse was called");
var features = geojson.read(resp.priv.responseText);
for (var i in features) {
var feature = features[i];
feature.attributes.iconUrl = katman.iconUrl;
feature.attributes.fillColor = katman.fillColor;
feature.attributes.fillOpacity = katman.fillOpacity;
feature.attributes.graphicHeight = katman.graphicHeight;
feature.attributes.graphicOpacity = katman.graphicOpacity;
feature.attributes.graphicWidth = katman.graphicWidth;
feature.attributes.graphicXOffset = katman.graphicXOffset;
feature.attributes.graphicYOffset = katman.graphicYOffset;
feature.attributes.pointRadius = katman.pointRadius;
feature.attributes.pointerEvents = katman.pointerEvents;
feature.attributes.rotation = katman.rotation;
feature.attributes.strokeColor = katman.strokeColor;
feature.attributes.strokeDashstyle = katman.strokeDashstyle;
feature.attributes.strokeLinecap = katman.strokeLinecap;
feature.attributes.strokeOpacity = katman.strokeOpacity;
feature.attributes.strokeWidth = katman.strokeWidth;
}
layer.addFeatures(features);
};

how to run at command through chrome serial api

i want to run at command at my hardware thorugh crome serial api
I use this Opensource code
https://github.com/GoogleChrome/chrome-app-samples/tree/master/servo
this working only for only integer
i want to pass string in the serial port my code is like following
var connectionId = -1;
function setPosition(position) {
var buffer = new ArrayBuffer(1);
var uint8View = new Uint8Array(buffer);
uint8View[0] = '0'.charCodeAt(0) + position;
chrome.serial.write(connectionId, buffer, function() {});
};
function setTxt(data) {
// document.getElementById('txt').innerHTML = data;
var bf = str2ab(data)
chrome.serial.write(connectionId, bf, function() {});
};
function str2ab(str) {
len = str.length;
var buf = new ArrayBuffer(len*2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
for (var i=0, strLen=str.length; i<strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
function onRead(readInfo) {
var uint8View = new Uint8Array(readInfo.data);
var value1 = String.fromCharCode(uint8View[0])
var value = uint8View[0] - '0'.charCodeAt(0);
var rotation = value * 18.0;
// var dataarr = String.fromCharCode.apply(null, new Uint16Array(readInfo.data));
//alert(rotation);
if(uint8View[0])
document.getElementById('txt').innerHTML = document.getElementById('txt').innerHTML + value1;
document.getElementById('image').style.webkitTransform =
'rotateZ(' + rotation + 'deg)';
// document.getElementById('txt').innerHTML=uint8View[0];
// Keep on reading.
chrome.serial.read(connectionId, 1, onRead);
};
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint16Array(buf));
}
function onOpen(openInfo) {
connectionId = openInfo.connectionId;
if (connectionId == -1) {
setStatus('Could not open');
return;
}
setStatus('Connected');
setPosition(0);
chrome.serial.read(connectionId, 1, onRead);
};
function setStatus(status) {
document.getElementById('status').innerText = status;
}
function buildPortPicker(ports) {
var eligiblePorts = ports.filter(function(port) {
return !port.match(/[Bb]luetooth/);
});
var portPicker = document.getElementById('port-picker');
eligiblePorts.forEach(function(port) {
var portOption = document.createElement('option');
portOption.value = portOption.innerText = port;
portPicker.appendChild(portOption);
});
portPicker.onchange = function() {
if (connectionId != -1) {
chrome.serial.close(connectionId, openSelectedPort);
return;
}
openSelectedPort();
};
}
function openSelectedPort() {
var portPicker = document.getElementById('port-picker');
var selectedPort = portPicker.options[portPicker.selectedIndex].value;
chrome.serial.open(selectedPort, onOpen);
}
onload = function() {
var tv = document.getElementById('tv');
navigator.webkitGetUserMedia(
{video: true},
function(stream) {
tv.classList.add('working');
document.getElementById('camera-output').src =
webkitURL.createObjectURL(stream);
},
function() {
tv.classList.add('broken');
});
document.getElementById('position-input').onchange = function() {
setPosition(parseInt(this.value, 10));
};
document.getElementById('txt-input').onchange = function() {
setTxt(this.value);
// document.getElementById('txt').innerHTML = this.value;
};
chrome.serial.getPorts(function(ports) {
buildPortPicker(ports)
openSelectedPort();
});
};
string is the passing through serial but this command not run without enter press how to do it any one know
thanks in advance :)
need a \n at the end of string
example:
writeSerial( '#;Bit_Test;*;1;' + '\n' );
take a look at this project http://www.dataino.it/help/document_tutorial.php?id=13

Categories

Resources