Using javascript, how convert to JSON, Java-POJO-like classes? - javascript

I want use Java-POJO-like classes in my JS project: only private fields, getters and setters.
function Event() {
var homeTeam;
var awayTeam;
var id;
var singleBets = [];
var bet;
...
this.getHomeTeam = function(){
return homeTeam;
}
this.setHomeTeam = function(data){
homeTeam = data;
}
this.getAwayTeam = function(){
return awayTeam;
}
this.setAwayTeam = function(data){
awayTeam = data;
}
this.getId = function(){
return id;
}
this.setId = function(data){
id = data;
}
this.getSingleBets = function(){
return singleBets;
}
this.setSingleBets = function(data){
singleBets = data;
}
this.getBet = function(){
return bet;
}
this.setBet = function(data){
bet = data;
}
}
I would convert my Java-POJO-like class in a JSON string to send it to the server.
I can't use JSON.stringify(myClass) because the fields are private.
So I think to use a recursive method like this...
var myJsonParse = function(data){
var result = "";
for(var propertyName in data) {
var method = propertyName;
if (method.substring(0,3)=="get"){
... data[propertyName].call() ...
}
}
return result;
}
...but before I spend many time to write it I want ask you if exist a better way to convert the Java-POJO-like object in JSON.
Thank you.
Update #1
I am ashamed of myself! This is my working (but absolutely temporary) solution:
this.toJSON = function() {
var bettableEventsString = [];
for (var i = 0, len = bettableEvents.length; i < len; i++) {
bettableEventsString[i] = bettableEvents[i].toJSON();
}
var result = JSON.stringify({
userId: userId,
championshipDayId: championshipDayId,
championshipDayName: championshipDayName
});
result = result.substring(0, result.length-1);
result += ',\n "bettableEvents" : [ ' + bettableEventsString + " ] ";
result += " } "
return result;
}

The only simple way I can think of is to add an export method:
this.toJSON = function() {
return JSON.stringify({
homeTeam: homeTeam,
awayTeam: awayTeam,
id: id,
// etc...
});
}

Related

toString method on Linked List implementation not working in js

I'm working through Cracking the Coding Interview and I thought I'd implement all the data structures in JS 5. Can anyone explain to me why my toString method isn't working?
Thanks!
function Node(data) {
this.next = null;
this.data = data;
}
Node.prototype.appendToTail = function(data) {
var end = new Node(data);
var n = this;
while (n.next != null) {
n = n.next;
}
n.next = end;
}
Node.prototype.toString = function(head) {
console.log(head)
if (head == null) {
return ""
} else {
return head.data.toString() + "-> " + head.next.toString();
}
}
var ll = new Node(1);
ll.appendToTail(3);
ll.appendToTail(4);
console.log(ll.toString())
function Node(data) {
this.next = null;
this.data = data;
}
Node.prototype.appendToTail = function(data) {
var end = new Node(data);
var n = this;
while (n.next != null) {
n = n.next;
}
n.next = end;
};
Node.prototype.toString = function() {
var returnValue = String(this.data);
if (this.next) {
returnValue = returnValue + "-> " + String(this.next);
}
return returnValue;
};
var ll = new Node(1);
ll.appendToTail(3);
ll.appendToTail(4);
console.log(String(ll))
or avoid this kind of problems completly and do not use prototype, class, this, call, etc
Your toString function takes an argument, but you're not passing it when you call toString.
If you want to access the node, you should use this, instead of passing in a value
Node.prototype.toString = function() {
var result = this.data.toString();
if (this.next) {
result += "-> " + this.next.toString();
}
return result;
}

meteor: conditional subscription in template level

i reuse the same template in other route with different data argument but using the same publication...
if i do normal pub/sub, the data being published as expected. but when i do conditional pub/sub like below, i fail to subscribe the data. console log return empty array,,,
server/publication.js
Meteor.publish('ACStats', function(cId, uId) {
var selectors = {cId:cId, uId:uId};
var options = {
fields: {qId:0}
};
return ACStats.find(selectors,options);
});
client/onCreated
Template.channelList.onCreated(function() {
this.disable = new ReactiveVar('');
if (FlowRouter.getRouteName() === 'profile') {
var self = this;
self.autorun(function() {
var penName = FlowRouter.getParam('penName');
var u = Meteor.users.findOne({slugName:penName});
if (u) {var uId = u._id;}
Meteor.subscribe('ACStats', null, uId);
});
} else{
var self = this;
self.autorun(function() {
var channelName = FlowRouter.getParam('channel');
var c = Channels.findOne({title:channelName});
if (c) {var cId = c._id;}
Meteor.subscribe('ACStats', cId, null);
});
}
});
console
ACStats.find().fetch() //return empty array
anyone have figured out my mistake ..??
thank You so much....
You can make two publications:
Meteor.publish ('ACStatsChannels', cId, function() {
});
Meteor.publish ('ACStatsUsers', uId, function() {
})
And then subscribe like this:
Template.channelList.onCreated(function() {
this.disable = new ReactiveVar('');
var self = this;
self.autorun(function() {
if (FlowRouter.getRouteName() === 'profile') {
var penName = FlowRouter.getParam('penName');
self.subscribe('ACStatsUsers', penName);
} else {
var channelName = FlowRouter.getParam('channel');
self.subscribe('ACStatsChannels', channelName);
}
});
});

Process javascript object from html lists

I have a html structure as,
<ul>
<li>data</li>
<li><strong>data</strong></li>
<li><span>data.name</span></li>
</ul>
I want to process it to javascript object something as below,
[
{
'index': 0,
'render': function (data) {
return data;
}
},
{
'index': 1,
'render': function (data) {
return '<strong>' + data + '</strong>';
}
},
{
'index': 2,
'render': function (data) {
return '' + data.name + '';
}
}
]
I tried this code but the data parameter which is a json object are not being resolved in render field content.
var obj = [];
$('ul li').each(function(i, content){
var row = {};
row.index = i;
row.render = function(data) {
return content;
};
obj.push(row);
});
What I am looking is this code should work,
var data = {};
data.name = 'Example';
data.link = 'http://example.com';
console.log(obj[2].render(data));
It must return Example as string.
Are you looking for a string concatenation?
https://jsfiddle.net/oeavo45w/
var obj = [];
$('ul li').each(function (i, content) {
var row = {};
row.index = i;
row.render = function (data) {
console.log(111, data)
return '' + data.name + ''
};
obj.push(row);
});
var data = {};
data.name = 'Example';
data.link = 'http://example.com';
console.log(obj[2].render(data));
Solution: Parse an HTML Object and Evaluate Text as data Variable
Grab content and split it on the variable name data, making sure to accommodate key names. Provide the resulting array to a render function that checks for key names and replaces the placeholders with data supplied in the render parameter.
var obj = [];
$('ul li').each(function(i, content){
var content_arr = content.innerHTML.split(/data\.?([^"<]+)?/);
var row = {};
row.index = i;
row.render = function(data) {
var return_string = '';
for ( ii in content_arr ) {
if ( ii % 2 ) {
if ( content_arr[ii] ) {
return_string += data[content_arr[ii]];
}
else if ( 'string' === typeof data ) {
return_string += data;
}
}
else { return_string += content_arr[ii]; }
}
return return_string;
};
obj.push(row);
});
// data object
var data = {};
data.name = 'EXAMPLE';
data.link = 'http://example.com';
// <span>EXAMPLE</span>
// or data string
data = 'testme';
console.log(obj[1].render(data));
// <strong>testme</strong>
http://jsfiddle.net/heksh7Lr/6/
(Ya, I'm guessing HTML template libraries will be more powerful.)

Loop closure returning function instead of string

I am trying to create a closure in my for loop, how ever, it keeps returning a function instead of a string.
$(function() {
var addID = function(id) {
var temp = id;
return function() {
return "http://localhost:3000/board/raptrex/" + temp;
}
};
$.get("http://localhost:3000/board/raptrex", function( data ) {
console.log(data);
var $deleteUL = $('#delete');
for (var i = 0; i < data.length; i++) {
var url = addID(data[i]._id);
console.log(url);
var $item = $('<li></li>').text(data[i].name).click(function() {
$.ajax({
type: "DELETE",
url: url
})
.done(function( msg ) {
alert( "Deleted: " + msg );
});
});
$deleteUL.append($item);
}
});
});
This returns http://localhost:3000/function%20()%20{%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20return%20%22http://localhost:3000/board/raptrex/%22%20+%20temp;%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20} when I click on my li element
You're returning a function instead of a string with addID. Try the following:
var addID = function(id) {
var temp = id;
return "http://localhost:3000/board/raptrex/" + temp;
};

Error extract keyword from Google search in Javascript?

I have a sample code:
function getKeyword() {
var instance = this;
var googlePattern = /(www\.google\..*)/;
this.params = function(parameters) {
var result = [];
var params = parameters.split("&");
for(var p in params) {
var kv = params[p].split("=");
result[kv[0]] = kv[1];
}
return result;
};
this.googleKeywords = function(params){
var query = params["q"];
var pattern = /"(.*?)"|(\w+)/g;
return decodeURIComponent(query).replace(/\+/g, " ").match(pattern);
};
this.parseReferrer = function(){
var result = [];
var pathAndParams = document.referrer.split("?");
if(pathAndParams.length == 2) {
var path = pathAndParams[0];
var params = this.params(pathAndParams[1]);
if(path.search(googlePattern) > 0) {
result = this.googleKeywords(params);
}
}
return result;
};
return this.parseReferrer();
}
And then:
<script type="text/javascript">
if (document.referrer && document.referrer != "") {
if (document.referrer.search(/google\.*/i) != -1){
var keyword = getKeyword();
alert(keyword);
} else {
alert('Not search from google');
}
} else {
alert('Not referrer');
}
</script>
Ex: when i search with keyword is "iphone 5", result not show alert("iphone 5") ? How to fix it ?
The JavaScript for in construct loops over more than just the entries in the array. If you want to use for in you need to make sure that you're only processing the actual parameters. This is easiest accomplished by checking for hasOwnProperty:
this.params = function(parameters) {
var result = [];
var params = parameters.split("&");
for(var p in params) {
if (params.hasOwnProperty(p))
{
var kv = params[p].split("=");
result[kv[0]] = kv[1];
}
}
return result;
};
Alternatively you can use a regular for loop over the array:
this.params = function(parameters) {
var result = [];
var params = parameters.split("&");
for(var i=0; i < params.length; i++) {
var kv = params[i].split("=");
result[kv[0]] = kv[1];
}
return result;
};

Categories