Knockout: Combining 2 custom bindings for digits - Financial data - javascript

good Day
I found the following two fiddles that does exactly what I want:
The first Fiddle gives me decimal notation.
The second Fiddle gives me digital grouping of numbers.
My Question: How do I combine both of them into one such that I can just use it like this:
<b data-bind="commaDecimalFormatter: myNumber">This will output both demical notation and digital grouping</b>
====================================================================================================================================================================
Fiddle 1 code:
// Formatting Functions
function formatWithComma(x, precision, seperator) {
var options = {
precision: precision || 2,
seperator: seperator || '.'
}
var formatted = parseFloat(x,10).toFixed( options.precision );
var regex = new RegExp(
'^(\\d+)[^\\d](\\d{' + options.precision + '})$');
formatted = formatted.replace(
regex, '$1' + options.seperator + '$2');
return formatted;
}
function reverseFormat(x, precision, seperator) {
var options = {
precision: precision || 2,
seperator: seperator || ','
}
var regex = new RegExp(
'^(\\d+)[^\\d](\\d+)$');
var formatted = x.replace(regex, '$1.$2');
return parseFloat( formatted );
}
// END: Formatting Functions
// Custom Binding - place this in a seperate .js file and reference it in your html
ko.bindingHandlers.commaDecimalFormatter = {
init: function(element, valueAccessor) {
var observable = valueAccessor();
var interceptor = ko.computed({
read: function() {
return formatWithComma( observable() );
},
write: function(newValue) {
observable( reverseFormat(newValue) );
}
});
if( element.tagName == 'INPUT' )
ko.applyBindingsToNode( element , {
value: interceptor
} );
else
ko.applyBindingsToNode( element , {
text: interceptor
} );
}
}
// this is your viewmodel
var vm = {
myNumber: ko.observable(100000)
}
// when the DOM is ready, call ko.applyBindings with your viewmodel
$(function() {
ko.applyBindings(vm);
});
FIDDLE 2 Code:
(function(){
var format = function(value) {
toks = value.toFixed(2).replace('-', '').split('.');
var display = '$' + $.map(toks[0].split('').reverse(), function(elm, i) {
return [(i % 3 === 0 && i > 0 ? ',' : ''), elm];
}).reverse().join('') + '.' + toks[1];
return value < 0 ? '-' + display : display;
};
ko.subscribable.fn.money = function() {
var target = this;
var writeTarget = function(value) {
var stripped=value
.replace(/[^0-9.-]/g, '');
target(parseFloat(stripped));
};
var result = ko.computed({
read: function() {
return target();
},
write: writeTarget
});
result.formatted = ko.computed({
read: function() {
return format(target());
},
write: writeTarget
});
result.isNegative = ko.computed(function(){
return target()<0;
});
return result;
};
})();
//Wire it up
$(function() {
var viewModel = {
Cash: ko.observable(1000000).money(),
};
viewModel.Total = ko.computed(function() {
return this.Cash();
}, viewModel).money();
ko.applyBindings(viewModel);
});

I cannot combine the two functions. Try the following, since it does what you want: Both Decimal notation and Digit grouping:
JS:
function formatPrice(price) {
return price.reverse().replace(/((?:\d{2})\d)/g, '$1 ').reverse();
}
// Need to extend String prototype for convinience
String.prototype.reverse = function() {
return this.split('').reverse().join('');
}
$('.myNumber').each(function(){
$(this).html(formatPrice($(this).html()));
});
See Fiddle
NOTE: You need to refresh the browser everytime for the jquery to format the output value(Read Only) into digit grouping...That is of course when you enter a new value into the editor screen(first field) and you don't see the digit grouping updated

I'd like to provide an alternative solution. You could also create a custom binding handler that does what you want (which would use the syntax you originally proposed).
ko.bindingHandlers. commaDecimalFormatter = {
update: function(element, valueAccessor, allValuesAccessor) {
// This gets the current value of the observable from your model
var value = ko.utils.unwrapObservable(valueAccessor());
// Manipulate `value` as desired using the bodies of the functions you mentioned
// Note: You don't want to use a global function, so actually take the bodies
// and put it here. Plain old JS :)
...
// Set the value on the element
jQuery(element).text(value);
}
};

Related

"Undefined" in the end of the accumulator.value()

I ran into the problem of the value misplacement in the constructor function method this.result. I do not understand why I'm get the result of the end of the function - undefined...
Tell me please, what is forgotten to include in the function :(
function Accumulator(startingValue) {
this.startingValue = startingValue;
this.read = function() {
this.a = +prompt('Your digit: ', '');
};
this.value = function() {
this.value += this.a;
};
this.result = function() {
return this.value + this.startingValue;
}
}
var accumulator = new Accumulator(1); // starting value 1
accumulator.read(); // sum prompt with current value
accumulator.read(); // sum current prompt with previous prompt and current value
console.log( accumulator.result() ); // display sum result
If .value is supposed to be an integer, don't define it as a function :-)
I think you should drop .value(), .startingValue and .a and just use .value everywhere. Put the summation directly into the read method. Simplify to:
function Accumulator(startingValue) {
this.value = startingValue;
this.read = function() {
// the temporary variable might be unnecessary but I left it in for verbosity
const a = +prompt('Your digit: ', '');
this.value += a;
};
this.result = function() {
return this.value;
};
}
var accumulator = new Accumulator(1); // starting value 1
accumulator.read(); // add prompt to current value
accumulator.read(); // add another prompt to current value
console.log( accumulator.result() ); // display sum by calling result() method
You might also want to define the methods on the prototype:
function Accumulator(startingValue) {
this.value = startingValue;
}
Accumulator.prototype.read = function() {
this.value += +prompt('Your digit: ', '');
};
Accumulator.prototype.result = function() {
return this.value;
};
and even use modern class syntax, as #ArtificialBug suggested:
class Accumulator {
constructor(startingValue) {
this.value = startingValue;
}
read() {
this.value += parseInt(prompt('Your digit: ', ''), 10);
}
result() {
return this.value;
}
}
There are two problems
this.value = function() {
this.value += this.a; //this.value is a function
};
and
console.log( accumulator.value ); // accumulator value is a function which needs to be invoked
Make it
function Accumulator(startingValue) {
this.startingValue = startingValue;
this.read = function() {
this.a = (this.a || this.startingValue ) + +prompt('Your digit: ', '');//initialize and add the prompted value
};
this.value = function() {
return this.a; //simply return the value
};
this.result = function() {
return this.a + this.startingValue; //this.a instead of this.value
}
}
var accumulator = new Accumulator(1);
accumulator.read();
accumulator.read();
console.log( accumulator.value() ); // invoke the method

LocalStorage and JSON.stringify JSON.parse

I have been working on a project that allows the user to submit memories about a place they have visited and tracks the location of when the memory was submitted. My only problem is trying to use localStorage with the app, I read about the JSON.stringify and JSON.parse, and don't understand how to use them in my code yet.
This is my form.js
It processes the form and grabs the text fields. It clears the form when the add button(on the display details page) or the enter details button is clicked. Finally it receives the information and sends out the message back to the window.
function processForm(){
var locate = document.myform.locate.value;
var details = document.myform.details.value;
var storeData = [];
localStorage.setItem("locate", JSON.stringify(locate));
localStorage.setItem("details", JSON.stringify(details));
alert("Saved: " + localStorage.getItem("locate") + ", and " + localStorage.getItem("details"));
var date = new Date,
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear(),
hour = date.getHours(),
minute = date.getMinutes(),
ampm = hour > 12 ? "PM" : "AM";
hour = hour % 12;
hour = hour ? hour : 12; // zero = 12
minute = minute > 9 ? minute : "0" + minute;
hour = hour > 9 ? hour : "0" + hour;
date = month + "/" + day + "/" + year + " " + hour + ":" + minute + " " + ampm;
localStorage.setItem("date", JSON.stringify(date));
storeData.push(locate, details, date);
localStorage.setItem("storeData", JSON.stringify(storeData));
}
function clearForm(){
$('#myform').get(0).reset();
}
function retrieveFormInfo(){
var data = JSON.parse(localStorage.getItem("storeData"));
var locate = JSON.parse(localStorage.getItem("locate"));
$("#locate2").html("Place: " + locate);
var details = JSON.parse(localStorage.getItem("details"));
$("#details2").html("Description: " + details);
var date = JSON.parse(localStorage.getItem("date"));
$("#date").html(date);
}
But the major problem I am running into is I do know how to take that information in correctly using the JSON.stringify and JSON.parse and appending it to the window with html elements dynamically, Mainly like a list of memories.
Any help is appreciated!
localStorage stores key value pairs as strings only (you can use integer for keys but they get converted to string automatically).
Storage objects are simple key-value stores, similar to objects, but they stay intact through page loads. The keys and the values are always strings (note that, as with objects, integer keys will be automatically converted to strings) reference
let's say you have an array to be stored with each item being a json object.
You got 2 options:
Option 1:
stringify every item and store in locaStorage
var item = {input1: 'input1value', input2: 'input2value' };
localStorage.setItem( itemIndex, JSON.stringify(item) );
to retrive the items iterate over localStorage items and then convert the item to JSON object:
for(var i=0;i<localStorage.length; i++) {
var key = localStorage.key( i );
var item = JSON.parse( localStorage.getItem( key ) );
}
Option 2:
stringify the entire array and store in localStorage
localStorage.setItem( 'memoriesdata', JSON.stringify( arr ) );
to read the data read the item as string then convert to JSON object
var arr = JSON.parse( localStorage.getItem('memoriesdata') );
First get values of your input fields into a javascript object.
var myMemory = {};
myMemory.location = document.getElementById('location').value;
myMemory.description = document.getElementById('description').value;
Now save myMemory to localStorage,this can be done on a form submission or a button press. We can store as an array of memories and add item to it every time.
//if user already has memories in local, get that array and push into it.
//else create a blank array and add the memory.
memories = localStorage.getItem('memories') ?
JSON.parse(localStorage.getItem('memories')) :
[];
memories.push(myMemory);
localStorage.setItem('memories', JSON.stringify(memories));
I use this Storage implementation. It's inspired by many storage plugins out there... It handles any value serilizable by JSON.stringify function, and should work xbrowser (and in 'cookie-disabled' firefox):
//
// api:
//
// .clear() empties storage
// .each() loops storage (key, value) pairs
// .fetch() get a value by key
// .has() checks if there is a key set
// .ls() lists all keys
// .raw() string value actually stored
// .reload() reads in serialized data
// .rm() removes key(s)
// .set() setup value(s)
// .type() storage type used 'localStorage/globalStorage/userData'
// .valid() is storage engine setup correctly
//
;
((function(name, def, glob, doc) {
// add 'store' id to globals
this[name] = def(glob, doc);
}).call(
this, "store", function(glob, doc) {
// private (function) store version
var stclient;
var driver = {
// obj : storage_native{},
// type : storage_type
};
var engine = {
// read : (func),
// write : (func)
};
var _ = {
a: Array.prototype,
del: function(node) { // , ...fields
_.slc(arguments, 1).
forEach(function(field) {
delete this[field];
}, node);
return node;
},
each: function(array, callback, context) {
context ||
(context = array);
array.
some(function() {
return false === callback.apply(context, arguments);
});
return array;
},
hasown: Function.prototype.call.bind(Object.prototype.hasOwnProperty),
jsdc: JSON.parse, // decode
jsec: JSON.stringify, // encode
keys: Object.keys, // shimed .keys
ns: "storage5", // single property name to keep serialized storage data under
object: null, // parsed storage data
slc: Function.prototype.call.bind(Array.prototype.slice),
test: {
isemptyobj: function(node) {
for (var x in node)
return false;
return true;
},
isplainobj: function(node) {
return '[object Object]' == Object.prototype.toString.call(node);
},
},
testval: 'storage' + Math.random(), // test value for implementation check
rig: function(target, items) {
for (var field in items)
if (items.hasOwnProperty(field))
target[field] = items[field];
return target;
},
clone: function(node) {
return _.jsdc(_.jsec(node));
},
puts: function() {
engine.write(_.jsec(_.object));
},
};
stclient = function storage5() {
return arguments.length ?
storage5.set.apply(storage5, arguments) :
storage5.fetch();
};
// _init on load|ready
window.addEventListener('load', _init, false);
return _.rig(stclient, {
clear: function() {
return _.object = {}, _.puts(), this;
},
each: function(callback, context) {
context ||
(context = this.fetch());
_.each(this.ls(), function(field) {
return callback.call(context, field, this.fetch(field));
}, this);
return this;
},
fetch: function(key) {
return (arguments.length) ?
_.object[key] : _.clone(_.object);
},
has: function(name) {
return _.hasown(_.object, name);
},
ls: function() {
return _.keys(_.object);
},
raw: function() {
return engine.read();
},
reload: _load,
rm: function() {
_.del.apply(null, _.a.concat.apply([_.object], arguments));
return _.puts(), this;
},
set: function(input, value) {
var len = arguments.length;
var flag = 1;
if (len) {
if (_.test.isplainobj(input)) {
_.keys(input).
forEach(function(field) {
_.object[field] = input[field];
});
} else {
if (1 < len)
_.object[input] = value;
else
flag = 0;
}
flag && _.puts();
}
return this;
},
type: function() {
return driver.type || null;
},
valid: function() {
return !_.test.isemptyobj(driver);
},
});
function _init() {
var flag = 0;
var stnative;
if ("localStorage" in glob) {
try {
if ((stnative = glob["localStorage"])) {
// inits localStorage
_initlocst(stnative, driver, engine);
flag = 1;
}
} catch (e) {}
}
if (!flag) {
if ("globalStorage" in glob) {
try {
if ((stnative = glob["globalStorage"])) {
// inits globalStorage
_initglobst(stnative, driver, engine);
flag = 1;
}
} catch (e) {}
}
if (!flag) {
// inits userDataStorage
_initusrdatast(doc.createElement(_.ns), driver, engine);
}
}
// parse serialized storage data
_load();
}
function _initlocst(stnative, driver, engine) {
stnative[_.testval] = _.testval;
if (_.testval === stnative[_.testval]) {
try {
stnative.removeItem(_.testval);
} catch (e) {
try {
delete stnative[_.testval];
} catch (e) {}
}
driver.obj = stnative;
driver.type = "localStorage";
engine.read = function() {
return driver.obj[_.ns];
};
engine.write = function(stringvalue) {
driver.obj[_.ns] = stringvalue;
return stringvalue;
};
}
}
function _initglobst(stnative, driver, engine) {
var host = glob.location.hostname;
driver.obj = (/localhost/i).test(host) ?
stnative["localhost.localdomain"] : stnative[host];
driver.type = "globalStorage";
engine.read = function() {
return driver.obj[_.ns];
};
engine.write = function(stringvalue) {
driver.obj[_.ns] = stringvalue;
return stringvalue;
};
}
function _initusrdatast(node, driver, engine) {
try {
node.id = _.ns;
node.style.display = "none";
node.style.behavior = "url('#default#userData')";
doc.
getElementsByTagName("head")[0].
appendChild(node);
node.load(_.ns);
node.setAttribute(_.testval, _.testval);
node.save(_.ns);
if (_.testval === node.getAttribute(_.testval)) {
try {
node.removeAttribute(_.testval);
node.save(_.ns);
} catch (e) {}
driver.obj = node;
driver.type = "userData";
engine.read = function() {
return driver.obj.getAttribute(_.ns);
};
engine.write = function(stringvalue) {
driver.obj.setAttribute(_.ns, stringvalue);
driver.obj.save(_.ns);
return stringvalue;
};
}
} catch (e) {
doc.
getElementsByTagName("head")[0].
removeChild(node);
}
node = null;
}
function _load() {
try {
_.object = _.jsdc((engine.read() || engine.write("{}")));
} catch (e) {
_.object = {};
}
}
}, window, document));
//eof
Vanilla JS:
var printStorageBody = function () {
var body = document.querySelector("body");
var pre = document.createElement("pre");
body.innerHTML = "";
pre.innerText = JSON.stringify(localStorage, null, '\t');
body.appendChild(pre);
}
jQuery:
var printStorageBody = function () {
$("body").html("");
$("<pre>")
.text(JSON.stringify(localStorage, null, '\t'))
.appendTo("body");
}

create an add/remove or refresh function in a boilerplate plugin

I have this simple plugin I am building which just builds a table:
; (function ($, window, document, undefined) {
// Create the defaults once
var pluginName = "tableBuilder",
defaults = {
};
// The actual plugin constructor
function Plugin(element, options) {
this.element = element;
// jQuery has an extend method that merges the
// contents of two or more objects, storing the
// result in the first object. The first object
// is generally empty because we don't want to alter
// the default options for future instances of the plugin
this.options = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
String.prototype.format = function (values) {
var regex = /\{([\w-.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g;
var getValue = function (key) {
var value = values,
arr, type;
if (values == null || typeof values === 'undefined') return null;
if (key.indexOf('.')) {
arr = key.split('.');
while (arr.length && value) {
value = value[arr.shift()];
}
} else {
value = val && val[key] || values[key];
}
type = typeof value;
return type === 'string' || type === 'number' ? value : null;
};
return this.replace(regex, function (match) {
//match will look like {sample-match}
//key will be 'sample-match';
var key = match.substr(1, match.length - 2);
var value = getValue(key);
return value != null ? value : match;
});
};
Plugin.prototype = {
init: function () {
// Place initialization logic here
// You already have access to the DOM element and
// the options via the instance, e.g. this.element
// and this.options
// you can add more functions like the one below and
// call them like so: this.yourOtherFunction(this.element, this.options).
this.cycle();
},
cycle: function() {
var self = this;
self.buildRow();
self.display();
},
buildRow: function () {
var self = this;
self.rows = [];
$.each(self.options.json, function (i, item) {
self.rows.push(self.options.rowTemplate.format(item));
});
console.log(self.rows);
},
display: function (el, options) {
var self = this;
$(self.element).html(self.rows.join());
}
};
// A really lightweight plugin wrapper around the constructor,
// preventing against multiple instantiations
$.fn[pluginName] = function (options) {
return this.each(function () {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName,
new Plugin(this, options));
}
});
};
})(jQuery, window, document);
I call this from a button click event:
var row = "<tr data-id=\"{Id}\"><td>{FileName}</td><td>{Metadata.FileSize}</td><td></td><td><button type=\"button\" class=\"close\" data-id=\"{Id}\" aria-hidden=\"true\">×</button></td></tr>"
$("#assets").on("click", ".glyphicon", function () {
var $asset = $(this).parent();
var $actionBar = $("#action-bar");
var $selected = $("#selected-asset");
var $table = $(".table");
var currentSelected = parseInt($selected.text());
var assetId = parseInt($asset.attr("id"))
if ($asset.hasClass("active")) {
$selected.text(currentSelected - 1);
activeItems = $.grep(activeItems, function (obj) {
return obj.Id != assetId
});
$asset.removeClass("active");
if (activeItems.length <= 0) {
$actionBar.hide();
}
} else {
$selected.text(currentSelected + 1);
var asset = $.grep(assets, function (obj) {
return obj.Id == assetId
});
activeItems.push(asset[0]);
$asset.addClass("active");
$actionBar.show();
}
$("#assets-table").tableBuilder({
json: activeItems,
rowTemplate: row
});
});
Now, when I click add the first time, the table is created. But each click after does nothing. I put a console.log on the buildRows function and it only gets called once, which is expected because we only instantiated the plugin on that element.
So, I need to add a refresh function or an add/remove function that is available to the client.
Can anyone give me a hand?
Ok, so I was not so impressed with my last answer.
With the help of this video:
Head first into plugin development
I was able to work out that all the functions are actually part of the plugin instance.
So, here is my new plugin :)
String.prototype.format = function (values) {
var regex = /\{([\w-.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g;
var getValue = function (key) {
var value = values,
arr, type;
if (values == null || typeof values === 'undefined') return null;
if (key.indexOf('.')) {
arr = key.split('.');
while (arr.length && value) {
value = value[arr.shift()];
}
} else {
value = val && val[key] || values[key];
}
type = typeof value;
return type === 'string' || type === 'number' ? value : null;
};
return this.replace(regex, function (match) {
//match will look like {sample-match}
//key will be 'sample-match';
var key = match.substr(1, match.length - 2);
var value = getValue(key);
return value != null ? value : match;
});
};
; (function ($, window, document, undefined) {
var pluginName = "tableBuilder",
defaults = {
};
function Plugin(element, options) {
this.element = element;
this.$element = $(element);
this.rows = [];
this.rowTemplate = (typeof options === "string") ? options : options.rowTemplate;
this.options = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function () {
this.cycle();
},
cycle: function () {
var self = this;
if (self.options.json != null) {
self.buildRow();
self.display();
}
if (typeof self.options.onComplete === "function") {
self.options.onComplete.apply(self.element, arguments);
}
},
buildRow: function () {
var self = this;
$.each(self.options.json, function (i, item) {
self.rows.push(self.rowTemplate.format(item));
});
},
display: function (el, options) {
this.$element.html(this.rows.join());
},
add: function (row) {
console.log("moo");
this.rows.push(this.options.rowTemplate.format(row));
this.display();
},
remove: function(row) {
var match = this.options.rowTemplate.format(row);
this.rows = $.grep(this.rows, function (obj) {
return obj != match;
});
this.display();
}
};
$.fn[pluginName] = function (options) {
return this.each(function () {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName,
new Plugin(this, options));
}
});
};
})(jQuery, window, document);
now, the functions I needed access to are add() and remove() so if you look at these lines:
$.fn[pluginName] = function (options) {
return this.each(function () {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName,
new Plugin(this, options));
}
});
};
they are actually passing the instance to the $.data array which allows me to call my instance with a line of code:
$("#assets-table").data("plugin_tableBuilder")
and because of this, I am able to call any function that is a part of that instance, like this:
$("#assets-table").data("plugin_tableBuilder").add(asset[0]); // Add a row to our widget
I hope this helps someone else :D
/r3plica
I am going to answer this myself :)
Basically I decided that this was not the best way to handle my widget, so I used the widget factory boilerplate to sort out my issue. I modified my click event to this:
$("#assets").on("click", ".glyphicon", function () {
var $asset = $(this).parent(); // Get our asset element
var $actionBar = $("#action-bar"); // Get the action bar
var $selected = $("#selected-asset");// Get our selected asset counter
var currentSelected = parseInt($selected.text()); // Get our current counter value
var assetId = parseInt($asset.attr("id")); // Get the asset id
var asset = $.grep(assets, function (obj) { // Find our asset from our array
return obj.Id == assetId;
});
if ($asset.hasClass("active")) { // If our asset is already selected, then we must unselect it
$selected.text(currentSelected - 1); // First, decrease our counter
tableWidget.tableBuilder("remove", asset[0]); // Then call our widget and remove the current asset from the table
activeItems = $.grep(activeItems, function (obj) { // Repopulate our array of active assets
return obj != asset;
});
$asset.removeClass("active"); // And remove the active class from our element
if (activeItems.length <= 0) { // Finally, if this is the only selected asset
$actionBar.hide(); // Hide our actionbar
}
} else { // Else, we are selecting an asset
$selected.text(currentSelected + 1); // Increase our counter
tableWidget.tableBuilder("add", asset[0]); // Add a row to our widget
activeItems.push(asset[0]); // Add the asset to our array of active assets
$asset.addClass("active"); // Add our active alss to our element
$actionBar.show(); // And show our actionbar
}
});
And I instantiated my plugin on the page load like this:
var row = "<tr data-id=\"{Id}\"><td>{FileName}</td><td>{Metadata.FileSize}</td><td></td><td><button type=\"button\" class=\"close\" data-id=\"{Id}\" aria-hidden=\"true\">×</button></td></tr>"
var tableWidget;
$(function () {
tableWidget = $("#assets-table").tableBuilder({
rowTemplate: row
});
});
and then, my script I rewrote to this:
/*!
* jQuery UI Widget-factory plugin boilerplate (for 1.8/9+)
* Author: #addyosmani
* Further changes: #peolanha
* Licensed under the MIT license
*/
String.prototype.format = function (values) {
var regex = /\{([\w-.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g;
var getValue = function (key) {
var value = values,
arr, type;
if (values == null || typeof values === 'undefined') return null;
if (key.indexOf('.')) {
arr = key.split('.');
while (arr.length && value) {
value = value[arr.shift()];
}
} else {
value = val && val[key] || values[key];
}
type = typeof value;
return type === 'string' || type === 'number' ? value : null;
};
return this.replace(regex, function (match) {
//match will look like {sample-match}
//key will be 'sample-match';
var key = match.substr(1, match.length - 2);
var value = getValue(key);
return value != null ? value : match;
});
};
; (function ($, window, document, undefined) {
// define your widget under a namespace of your choice
// with additional parameters e.g.
// $.widget( "namespace.widgetname", (optional) - an
// existing widget prototype to inherit from, an object
// literal to become the widget's prototype );
$.widget("skipstone.tableBuilder", {
//Options to be used as defaults
options: {
json: null,
rowTemplate: null
},
//Setup widget (eg. element creation, apply theming
// , bind events etc.)
_create: function () {
// _create will automatically run the first time
// this widget is called. Put the initial widget
// setup code here, then you can access the element
// on which the widget was called via this.element.
// The options defined above can be accessed
// via this.options this.element.addStuff();
this.rows = [];
if (this.options.json != null) {
this._buildRow();
this._display();
}
},
_buildRow: function () {
var self = this;
$.each(self.options.json, function (i, item) {
self.rows.push(self.options.rowTemplate.format(item));
});
},
_display: function (el, options) {
$(this.element).html(this.rows.join());
},
add: function (row) {
this.rows.push(this.options.rowTemplate.format(row));
this._display();
},
remove: function(row) {
var match = this.options.rowTemplate.format(row);
this.rows = $.grep(this.rows, function (obj) {
return obj != match;
});
this._display();
},
// Destroy an instantiated plugin and clean up
// modifications the widget has made to the DOM
destroy: function () {
// this.element.removeStuff();
// For UI 1.8, destroy must be invoked from the
// base widget
$.Widget.prototype.destroy.call(this);
// For UI 1.9, define _destroy instead and don't
// worry about
// calling the base widget
}
});
})(jQuery, window, document);
This how now fixed my issue. You can see that I add rows by calling
tableWidget.tableBuilder("add", asset[0]);
and remove items by calling:
tableWidget.tableBuilder("remove", asset[0]);
I really hope that helps someone else :D
Cheers,
r3plica

Getter in object isn't returning a value Javascript

I have a problem with return a value from an object.
my object looks like this.
function XYZ(date, startT)
{
var _date=date;
var _startT=startT;
this.get_date = function() {
return _date;
};
this.set_date = function(value) {
_date=value;
};
this.get_startT = function() {
return _startT;
};
this.set_startT = function(value) {
_startT=value;
};
this.toString()
return (_date + " " _startT);
}
then i create an Array like this
jsData[0] =new XYZ("2012-11-11","8:00");
jsData[1] = new XYZ("2012-03-03","8:00");
when i want to use get_date method it didn't return me the value but the get_startT method works fine.
When i show object with .toString method it also show me full object
Please help.
It works if you fix all the syntax errors:
function XYZ(date, startT) {
var _date=date;
var _startT=startT;
this.get_date = function() {
return _date;
};
this.set_date = function(value) {
_date=value;
};
this.get_startT = function() {
return _startT;
};
this.set_startT = function(value) {
_startT=value;
};
}
var jsData = [];
jsData[0] = new XYZ("2012-11-11","8:00");
jsData[1] = new XYZ("2012-03-03","8:00");
display("jsData[0].get_date() = " + jsData[0].get_date());
Output:
jsData[0].get_date() = 2012-11-11
Live Copy | Source
Other than obvious typos, here's what I did:
Put { and } around the function body.
Removed the this.toString() which was non-functional (a no-op, as you didn't store the result anywhere).
Removed the return at the end, because returning a string primitive out of a constructor function is another no-op.
Declared jsData.
Initialized jsData.
You appear to be missing a opening bracket { after
function XYZ(date, startT)
And one at the end of your code. (})
Try adding methods to the function prototype like this:
function XYZ(date, startT) {
this._date = date;
this._startT = startT;
}
XYZ.prototype.get_date = function() {
return this._date;
}
XYZ.prototype.set_date = function(value) {
this._date = value;
}
XYZ.prototype.get_startT = function() {
return this._startT;
}
XYZ.prototype.set_startT = function(value) {
this._startT = value;
}
XYZ.prototype.toString = function() {
return this._date + " " + this._startT;
}
var myXYZ = new XYZ("2012-11-11","8:00");
myXYZ.toString(); // "2012-11-11 8:00"
I tested that in the console and it outputs the final string correctly.

Add space between numbers/digits and letters/characters

I have a code like this
(function($, window, document, undefined) {
$.fn.quicksearch = function (target, opt) {
var timeout, cache, rowcache, jq_results, val = '', e = this, options = $.extend({
delay: 100,
selector: null,
stripeRows: null,
loader: null,
noResults: '',
bind: 'keyup',
onBefore: function () {
return;
},
onAfter: function () {
return;
},
show: function () {
this.style.display = "";
},
hide: function () {
this.style.display = "none";
},
prepareQuery: function (val) {
return val.toLowerCase().split(' ');
},
testQuery: function (query, txt, _row) {
for (var i = 0; i < query.length; i += 1) {
if (txt.indexOf(query[i]) === -1) {
return false;
}
}
return true;
}
}, opt);
this.go = function () {
var i = 0,
noresults = true,
query = options.prepareQuery(val),
val_empty = (val.replace(' ', '').length === 0);
for (var i = 0, len = rowcache.length; i < len; i++) {
if (val_empty || options.testQuery(query, cache[i], rowcache[i])) {
options.show.apply(rowcache[i]);
noresults = false;
} else {
options.hide.apply(rowcache[i]);
}
}
if (noresults) {
this.results(false);
} else {
this.results(true);
this.stripe();
}
this.loader(false);
options.onAfter();
return this;
};
this.stripe = function () {
if (typeof options.stripeRows === "object" && options.stripeRows !== null)
{
var joined = options.stripeRows.join(' ');
var stripeRows_length = options.stripeRows.length;
jq_results.not(':hidden').each(function (i) {
$(this).removeClass(joined).addClass(options.stripeRows[i % stripeRows_length]);
});
}
return this;
};
this.strip_html = function (input) {
var output = input.replace(new RegExp('<[^<]+\>', 'g'), "");
output = $.trim(output.toLowerCase());
return output;
};
this.results = function (bool) {
if (typeof options.noResults === "string" && options.noResults !== "") {
if (bool) {
$(options.noResults).hide();
} else {
$(options.noResults).show();
}
}
return this;
};
this.loader = function (bool) {
if (typeof options.loader === "string" && options.loader !== "") {
(bool) ? $(options.loader).show() : $(options.loader).hide();
}
return this;
};
this.cache = function () {
jq_results = $(target);
if (typeof options.noResults === "string" && options.noResults !== "") {
jq_results = jq_results.not(options.noResults);
}
var t = (typeof options.selector === "string") ? jq_results.find(options.selector) : $(target).not(options.noResults);
cache = t.map(function () {
return e.strip_html(this.innerHTML);
});
rowcache = jq_results.map(function () {
return this;
});
return this.go();
};
this.trigger = function () {
this.loader(true);
options.onBefore();
window.clearTimeout(timeout);
timeout = window.setTimeout(function () {
e.go();
}, options.delay);
return this;
};
this.cache();
this.results(true);
this.stripe();
this.loader(false);
return this.each(function () {
$(this).bind(options.bind, function () {
val = $(this).val();
e.trigger();
});
});
};
}(jQuery, this, document));
I try to figure out where and how I can make a split/add space between numbers and letters. Cause some people type for example "ip1500" and the script cant match the input with an element that is like "ip 1500". My problem ist that Im a js beginner.
I was trying and trying but i cant get it work. I also tried this
I found this spot and I think it can be done here where the everything get splitted by an " " (space):
prepareQuery: function (val) {
return val.toLowerCase().split(' ');
},
Would be very nice if somebody can help me.
If you want "123abc345def" to "123 abc 345 def". The replace function may help. The code is like this.
var str = "123abc345def";
str = str.replace(/(\d+)/g, function (_, num){
console.log(num);
return ' ' + num + ' ';
});
str = str.trim();
The code you linked didn't work mainly because it's using a different programming language to javascript. In theory, it should work, but javascript does not support regular expression lookbehinds (at this present time)..
Instead, I have re-wrote that fragment of code:
prepareQuery: function (val) {
function isNotLetter(a){
return (/[0-9-_ ]/.test(a));
}
var val=val.toLowerCase().split("");
var tempArray=val.join("").split("");
var currentIndex=1;
for (var i=0;i<val.length-1;i++){
if (isNotLetter(val[i]) !== isNotLetter(val[i+1])){
tempArray.splice(i+currentIndex, 0, " ");
currentIndex++;
}
}
return tempArray.join("");
}
Since you're new to javascript, I'm going to explain what it does.
It declares a function in prepareQuery to check whether or not a string contains a letter [this can be moved somewhere else]
It then splits val into an array and copies the content of val into tempArray
An index is declared (explained later)
A loop is made, which goes through every single character in val
The if statement detects whether or not the current character (val[i] as set by the loop) is the same as the character next to it (val[i+1]).
IF either one are different to the other (ie the current character is a letter while the next isn't) then a space is added to the tempArray at that "index"
The index is incremented and used as an offset in #6
The loop finishes, joins the "array" into a string and outputs the result.
DEMO:
http://jsbin.com/ebitus/1/edit
(JSFiddle was down....)
EDIT:
Sorry, but I completely misinterpreted your question... You failed to mention that you were using "quicksearch" and jQuery. In that case I'm assuming that you have a list of elements that have names and you want to search through them with the plugin...
A much easier way to match the user's query (if there is no space) is to strip the space from the search table along with the query itself - though original reverse method will work (just not as efficiently) [aka: expanding the user's query]
In this case, stripping the space from both the search table and user input would be a better method
prepareQuery: function (val) {
return val.toLowerCase().replace(/ /ig,'').split(" ");
},
testQuery: function (query, txt, _row) {
txt=txt.toLowerCase().replace(/ /ig,'');
for (var i = 0; i < query.length; i += 1) {
if (txt.indexOf(query[i]) === -1) {
return false;
}
}
return true;
}
DEMO:
http://jsfiddle.net/q9k9Y/3/
Edit 2:
It seems like your real intent is to create a fully functioning search feature on your website, not to just add spaces between letters and numbers. With this, I suggest using Quicksilver. I would love to work out an algorithm to extend quickSearcher but at the current time I cannot (timezones). Instead, I suggest using Quicksilver
http://jsbin.com/oruhet/12/

Categories

Resources