Trouble defining method for Javascript class definition - syntax-error

I'm somewhat new to object oriented programming in Javascript and I'm trying to build a handler object and library for a list of items I get back from an API call. Ideally, I'd like the library functions to be members of the handler class. I'm having trouble getting my class method to work however. I defined as part of the class bcObject the method getModifiedDateTime, but when I try to echo the result of the objects call to this method, I get this error:
Error on line 44 position 26: Expected ';'
this.getModifiedDateTime: function(epochtime) {
which leads me to believe that I simply have a syntax issue with my method definition but I can't figure out where.
response(
{
"items":
[
{"id":711,"name":"Shuttle","lastModifiedDate":"1268426336727"},
{"id":754,"name":"Formula1","lastModifiedDate":"1270121717721"}
],
"extraListItemsAttr1":"blah",
"extraListItemsAttr2":"blah2"
});
function response(MyObject) {
bcObject = new bcObject(MyObject);
thing = bcObject.getModifiedDateTime(bcObject.videoItem[0].lastModifiedDate);
SOSE.Echo(thing);
}
function bcObject(listObject) {
// define class members
this.responseList = {};
this.videoCount = 0;
this.videoItem = [];
this.responseListError = "";
// instantiate members
this.responseList = listObject;
this.videoCount = listObject.items.length;
// populate videoItem array
for (i=0;i<this.videoCount;i++) {
this.videoItem[i] = listObject.items[i];
}
this.getModifiedDateTime: function(epochtime) {
var dateStringOutput = "";
var myDate = new Date(epochtime);
dateStringOutput = myDate.toLocaleString();
return dateStringOutput;
};
}

You use = to assign values in JS, not ::
this.getModifiedDateTime = function(epochtime) {

You should use the = operator for methods defined as you did there (this.<methodName> = function (...) {).
The colon notation is used when declaring object literals.

Related

Vue.js 3 JavaScript Objects members losing ref reactivity

I'm updating a web app from using Knockout.js Templates to Vue 3 Components. This issue is not in the components but in the JS where I'm creating objects to be used in the components.
I'm running into strange behaviour around using refs where an object member is not always being set as a ref. I haven't been able to recreate this in an example but a simplified version of the structure is that we have an attribute that returns an object that contains the ref value.
function Attribute(val) {
var value = ref(val);
return {
value: value
}
}
We have a builder that is used to add labels and other items such permissions and classes to the UI.
function UIBuilder() {
var self = this;
var newElement = {};
function newText(value) {
newElement.inputType = 'TEXT';
newElement.value = value;
return self;
}
function addLabel(lbl) {
newElement.label = lbl;
return self;
}
function build() {
return newElement;
}
this.newText = newText;
this.addLabel = addLabel;
this.build = build;
}
Finally there is a function that returns an object that contains everything that the component needs.
function TextInput(initValue) {
var self = this;
self.label = initValue.label;
self.value = initValue.value;
var textInput = {
label: self.label,
value: self.value
};
return textInput;
}
Then I create an object to be passed to the component.
var attr = new Attribute(5225);
var textBox = new TextInput(new UIBuilder().newText(attr).addLabel('Description').build());
This structure works using Knockout and I'm trying to keep as much of the existing code as possible.
Most of the time this works but there are some occasions where the value is coming in as a string rather then a ref. I haven't been able to isolate why this is happening. While debugging most of the time the values for initValue.value and self.value look like this in the watch on VS Code.
On some occasions it changes to string values even though the objects were created using the same functions.
I checked the initValue object when taking the screenshot and it appeared to be a ref
As far as I can see the value should stay as a ref. I'm not unwrapping it in code. Why is this happening? What should I look for?

dynamic parameter not working in a Put method

I'm migrating a solution from asp net to asp net core. When I tested this method
[HttpPut, Route("SearchPrices")]
public dynamic SearchPrices(dynamic data)
{
var list = from ma in db.Materials
select new
{
ma.MaterialID,
ma.MaterialTypeID,
ma.StatusID,
ma.Horsepower,
ma.MaterialPrice
};
list = list.OrderBy(s => s.MaterialID);
string filterString = data.filterString;
if (!string.IsNullOrEmpty(filterString))
{
list = list.Where(ma => new[] {
ma.MaterialID,
ma.MaterialPrice.ToString(),
ma.MaterialTypeID
}.Any(c => c.Contains(filterString)));
}
dynamic sort = data.sort;
string column = sort.column;
if (!string.IsNullOrEmpty(column))
{
bool reverse = sort.reverse;
list = list.OrderByColumn(column, reverse);
}
return FilterByColumn(list, data);
}
I receive a parameter with something like
ValueKind = Object : "{"filterString":"","options":[],"skipNumber":0,"takeNumber":50,"sort":{"column":"","reverse":false}}"
In which I cant make it work like it used to before, it throws a error when it tries to resolve "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''System.Text.Json.JsonElement' does not contain a definition for 'filterString''".
I've already tried some solutions to deserialize, but they didn't work.

Extending String native type in Typescript

I would like to extend the String type in Typescript.
Here's my code :
export class Str extends String{
constructor(str: string) {
super(str);
}
}
The problem is, after the call of the String constructor using super(str), the value of my new type stills empty.
I have the same problem with another type extending the native Array type.
Your code is transpiled to:
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Str = (function (_super) {
__extends(Str, _super);
function Str(str) {
_super.call(this, str);
}
return Str;
})(String);
And the problem is that you no longer deal with the original native type that has special properties (like + operator on two strings). So your extended type - even if you would have succeded - would be severely limited and confusing for others.
Details and gotchas can be found Axel Rauschmayer's article: http://www.2ality.com/2013/03/subclassing-builtins-es6.html

Creating new upshot js entities

I'm building a site as a Single Page Application using ASP.NET MVC 4 Beta .
The sample app talks about adding new entities and it uses a constructor function for it's product entity.
However I have many entity types and I'm not going to write a constructor function for each one. This is how I am creating a new entity (name is the name of the datasource and dataTarget.upshot.upshotData is the list of entities I get back from the GetEntities method
in coffeeScript...
newItem = {}
for field, def of upshot.metadata(upshot.dataSources[name]._entityType).fields
do (field, def) ->
if def.array
newItem[field] = new ko.observableArray()
else
newItem[field] = new ko.observable()
upshot.addEntityProperties newItem, upshot.dataSources[name]._entityType
dataTarget.upshot.upshotData.push newItem
my question is if this is the best way to do it or am I missing something? I'm surprised that upshot does not seem to have a createEntity method.
in javascript...
newItem = {};
_ref = upshot.metadata(upshot.dataSources[name]._entityType).fields;
_fn = function(field, def) {
if (def.array) {
return newItem[field] = new ko.observableArray();
} else {
return newItem[field] = new ko.observable();
}
};
for (field in _ref) {
def = _ref[field];
_fn(field, def);
}
upshot.addEntityProperties(newItem, upshot.dataSources[name]._entityType);
dataTarget.upshot.upshotData.push(newItem);
var newThing = {};
var typeName = "MyType:#MyNamespace";
upshot.map({ SomeProperty: "my value" }, typeName, newThing);
upshot.addEntityProperties(newThing, typeName);
This will create your object with the entity properties mapped to observables, and will allow you to set properties (see SomeProperty:"my value").

Generate parameter list with userdefined types at runtime (using C#)

As part of my project, I am trying to build a web UI where user will select a method and pass the values. My program should be able to call the method dynamically and build a parameter list on runtime to pass it to the method.
I have created a comma separated list (string) of key and value pairs. This key/value pair is nothing but the parameter name and value of my method (methodname stored in a variable). Example: string params = "ID:123;Name:Garry;Address:addressObject;AddressLine:108 Plaza Lane;City:Avenel;State:NJ;Zip:07001;". Where ID and Name are simple string varaibles while Address is user defined type. What follows after Address i.e. AddressLine, City, State and Zip is elements of Address object. And my method definition is
public string GetInfo(string ID, string Name, Address addressObject)
{
//return something;
}
I am dynamically calling the method (GetInfo) that is stored in sMethodName variable using DynamicProxy like :
string sMethodName = "GetInfo";
object result = (object) proxy.CallMethod(sMethodName, arguments);
Challenge is how to pass the argument list dynamically? Till now I am just able to extract the values from the csv variable into NamedValueCollection. Here is the code:
public static void StoreParameterValues(string param)
{
nvc = new NameValueCollection();
param = param.TrimEnd(';');
string[] parameters = param.Split(new char[] { ';' });
foreach (string val in parameters)
{
string[] keyValue = val.Split(new char[] { ':' });
nvc.Add(keyValue[0], keyValue[1]);
}
}
..and here is the code that tries to build the parameter:
string methodName = "GetInfo";
DynamicProxyFactory factory = new DynamicProxyFactory("http://../myservice.svc");
string sContract = "";
foreach (ServiceEndpoint endpoint in factory.Endpoints)
{
sContract = endpoint.Contract.Name;
}
DynamicProxy proxy = factory.CreateProxy(sContract);
string[] values = null;
// Create the parameter list
object[] arguments = new object[nvc.Count];
int i = -1;
foreach (string key in nvc.Keys)
{
values = nvc.GetValues(key);
foreach (string value in values)
{
arguments[++i] = value;
}
}
object result = (object) proxy.CallMethod(methodName, arguments);
The above code works if I have simple primitive types but not sure how can I build the logic for any other userdefined types. How can I create a object dynamically of type stored in a variable? Not sure if I was able to put my question correctly. I hope so :)
Edit: 01/19/2011: Applied the suggestion from Chris - using Reflection instead of ComponentModel.
I have converted the code to make it more generic. This works now for all primitive and custom types (resursion). Code snippet below:
private object BuildParameterList(Type type)
{
object item = new object();
item = Activator.CreateInstance(type);
PropertyInfo[] propArray = type.GetProperties(BindingFlags.Public|BindingFlags.Instance);
for (int i = 0; i < propArray.Length; i++)
{
PropertyInfo pi = (PropertyInfo)propArray[i];
////Check for custom type
if (IsCustomType(pi.PropertyType))
{
object item1 = BuildParameterList(pi.PropertyType);
pi.SetValue(item, item1, null);
}
else
{
if (property.ContainsKey(pi.Name))
{
pi.SetValue(item, Convert.ChangeType(property[pi.Name], pi.PropertyType), null);
}
}
}
return item;
}
But if one of the property is Color (I just tested with Color type, will fail with other system types aswell-i guess), then it fails at the following line. Not sure how to handle system types - Color or something similar.
pi.SetValue(item, Convert.ChangeType(property[pi.Name], pi.PropertyType), null);
Can you not find what types are expected by the method, by inspecting its ParameterInfos:
endpoint.Contract.ContractType.GetMethod(methodName).GetParameters();
and then instantiating the custom types using:
Activator.CreateInstance(parameterType);