Process javascript object from html lists - javascript

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.)

Related

How to access object array using javascript with variable

var dict = {
"configMigratedTo": {
"message": "Migrated configuration to configurator: $1"
}
}
var parametersForTranslation = {};
function __tr(src, params) {
parametersForTranslation[src] = params;
return buildMessage(src);
}
function buildMessage(src){
var message=dict[src] ? dict[src].message : src
console.log(message);
var messageArray = message.split("$");
var output = "";
messageArray.forEach(function(elem, index){
if(index === 0){
output += elem;
}else{
// get variable and index
var paramIndex = configMigratedTo.substring(0, 1);
var paramValue = parametersForTranslation[src][paramIndex-1];
output += paramValue;
output += configMigratedTo.substring(1);
}
});
return output;
}
__tr("configMigratedTo", [2]);
console.log(buildMessage("configMigratedTo"));
i want get result like __tr("configMigratedTo", [2]);
then it will give me
Migrated configuration to configurator: 2
i do not know where is wrong in my code
Try this one. Hope it helps!
var dict = {
"configMigratedTo": {
"message": "Migrated configuration to configurator: $1"
}
}
function __tr(src, params)
{
for (var key in dict)
{
if (key === src)
{
var message = dict[key].message;
return message.substring(0, message.length - 2) + params[0];
}
}
return;
}
console.log(__tr("configMigratedTo", [2]))
https://jsfiddle.net/eLd9u2pq/
Would that be enought?
var dict = {
"configMigratedTo": {
"message": "Migrated configuration to configurator: "
}
}
function buildMessage(src,param){
var output = dict[src].message + param;
return output;
}
console.log(buildMessage("configMigratedTo",2));
You are overcomplicating this, it's much easier using a regex and passing a function as replacer
var dict = {
"configMigratedTo": {
"message": "Migrated configuration to configurator: $1"
}
}
function __tr(src, params) {
if (! dict[src]) return src;
if (! /\$0/.test(dict[src].message)) params.unshift('');
return dict[src].message.replace(/\$(\d)+/g, (orig, match) => params[match] || orig);
}
console.log(__tr("configMigratedTo", [2]));

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

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...
});
}

How to feed a class a list of options through a function?

I'm trying out classes in javascript also using extend.js to create them. I am having some trouble with classes and am not really sure if I need them, but I think this one will be useful. It's a class to just get some database table data.
var TableData = Class.extend(function(){
this.rowId;
this.action;
this.returnWhat;
this.tableType;
this.php;
this.query = function(){
if (this.returnWhat) this.action += '_' + this.returnWhat;
var postData = { func : this.action };
if (this.rowId) $.extend(postData, { rowId : this.rowId });
$.post(this.php, postData, function(data){
if(data){this.data = data;}
});
return this.data;
};
});
I will have only tables that I know of, so I just store them as vars/options, but I don't know how to set the class vars up properly. This for example does not work but maybe demonstrates what I'm trying to do.
var options = {
rowId : '*',
action : 'get',
returnWhat : 'all'
}
var league = function (options){
this.tableType = 'league';
this.rowId = options.rowId;
this.action = options.action;
this.returnWhat = options.returnWhat;
this.php = 'php/' + options.tableType + '.php';
}
var tableData = new TableData(assoc_league);
I always like this idea
(function(my, $){
var cfg = {
rowId: null,
action: null,
returnWhat: null,
tableType: null,
url: null
};
my.init = function(options) {
if (options != undefined) {
for (var k in options) {
if (!options.hasOwnProperty(k)) continue;
cfg[k] = options[k];
}
}
return this;
};
my.fetchData = function(data, callback) {
$.post(cfg.url, data, function(resp) {
callback(resp);
});
}
})(window.myapp, window.jQuery);
//---------------
myapp.init({
url: '/blah/blah'
})
.fetchData({animal1: 'monkey', animal2: 'zebra'}, function(data){
});

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;
};

ko foreach with ko.computed is coping the input value to next input

I have an observable string witch contains a list of options.
Every single option is separated by this symbol "-*!*-"
There is also a computed function called optionsSplitted which is responsible to return an array of options.
This array is used from the foreach binding.
There is also a button to add options.
Everything works fine on the model, I can edit my options, add a new one.
But when I add some options and then edit one, it will be copied to the next one. Why???
jsfiddle
function ViewModel(args) {
var self = this;
self.activeAttributes = ko.observable({
options: ko.observable('a-*!*-b-*!*-c')
});
self.activeAttributes.optionsSplitted = ko.computed(function(){
return self.activeAttributes().options().split("-*!*-");
});
self.changed = function (data) {
var options = "", optionsSize = $('.option').length;
$('.option').each(function(i){
if(i < optionsSize - 1)
options += $(this).val() + "-*!*-";
else
options += $(this).val();
});
self.activeAttributes().options(options);
alert("Options: " + options)
};
self.addOption = function(data) {
self.activeAttributes().options(self.activeAttributes().options() + "-*!*-");
};
}
var model = {
};
var viewModel = new ViewModel(model);
ko.applyBindings(viewModel);
Using the ko.utils.arrayMap utility is fine.
jsfiddle
function ViewModel(args) {
var self = this;
self.activeAttributes = ko.observable({
options: ko.observable('a-*!*-b-*!*-c')
});
self.activeAttributes.optionsSplitted = ko.computed(function(){
var options = self.activeAttributes().options().split("-*!*-");
return ko.utils.arrayMap(options, function (option) {
return {
value: ko.computed({
read: function () { return option; }
})
};
});
});
self.changed = function (data) {
var options = "", optionsSize = $('.option').length;
$('.option').each(function(i){
if(i < optionsSize - 1)
options += $(this).val() + "-*!*-";
else
options += $(this).val();
});
self.activeAttributes().options(options);
alert("Options: " + options)
};
self.addOption = function(data) {
self.activeAttributes().options(self.activeAttributes().options() + "-*!*-");
};
};
var model = {
};
var viewModel = new ViewModel(model);
ko.applyBindings(viewModel);

Categories