How to stop Coffeescript from escaping keywords? - coffeescript

I am trying to write a indexeddb function "delete". It should read like this in JS:
var transaction = db.transaction('objectStore','readwrite');
var objectStore = transaction.objectStore('objectStore');
objectStore.delete(id);
However, when I write it in CS:
transaction = db.transaction 'objectStore','readWrite'
objectStore = transaction.objectStore 'objectStore'
objectStore.delete(id)
Of course it outputs:
...
objectStore["delete"](id);
I didn't write a method for IDBTransaction called "delete", but I have to use it. How can I keep CS from escaping the "delete" method and turning it into a "delete" key in an object?

Use backticks to pass through bare Javascript:
`objectStore.delete(id)`
will be compiled through verbatim. Try it here at my favorite site for interpreting between CS and JS: http://js2coffee.org/#coffee2js
transaction = db.transaction 'objectStore','readWrite'
objectStore = transaction.objectStore 'objectStore'
`objectStore.delete(id)`
becomes
var objectStore, transaction;
transaction = db.transaction('objectStore', 'readWrite');
objectStore = transaction.objectStore('objectStore');
objectStore.delete(id);

Why do you care that the JavaScript version is objectStore["delete"](id)? That's the same as objectStore.delete(id).
For example, if you say this in CoffeeScript:
class B
m: (x) -> console.log("B.m(#{x})")
class C extends B
c = new C
c.m('a')
c['m']('b')
The last two lines come out as this JavaScript:
c.m('a');
c['m']('b');
but they both call the same method.
Demo: http://jsfiddle.net/ambiguous/XvNzB/
Similarly, if you say this in JavaScript:
var o = {
m: function(x) { console.log('m', x) }
};
o.m('a');
o['m']('b');
The last two lines call the same method.
Demo: http://jsfiddle.net/ambiguous/Y3eUW/

Related

How to print fields with numeric names in mongo shell? [duplicate]

I'm trying to access a property of an object using a dynamic name. Is this possible?
const something = { bar: "Foobar!" };
const foo = 'bar';
something.foo; // The idea is to access something.bar, getting "Foobar!"
There are two ways to access properties of an object:
Dot notation: something.bar
Bracket notation: something['bar']
The value between the brackets can be any expression. Therefore, if the property name is stored in a variable, you have to use bracket notation:
var something = {
bar: 'foo'
};
var foo = 'bar';
// both x = something[foo] and something[foo] = x work as expected
console.log(something[foo]);
console.log(something.bar)
This is my solution:
function resolve(path, obj) {
return path.split('.').reduce(function(prev, curr) {
return prev ? prev[curr] : null
}, obj || self)
}
Usage examples:
resolve("document.body.style.width")
// or
resolve("style.width", document.body)
// or even use array indexes
// (someObject has been defined in the question)
resolve("part.0.size", someObject)
// returns null when intermediate properties are not defined:
resolve('properties.that.do.not.exist', {hello:'world'})
In javascript we can access with:
dot notation - foo.bar
square brackets - foo[someVar] or foo["string"]
But only second case allows to access properties dynamically:
var foo = { pName1 : 1, pName2 : [1, {foo : bar }, 3] , ...}
var name = "pName"
var num = 1;
foo[name + num]; // 1
// --
var a = 2;
var b = 1;
var c = "foo";
foo[name + a][b][c]; // bar
Following is an ES6 example of how you can access the property of an object using a property name that has been dynamically generated by concatenating two strings.
var suffix = " name";
var person = {
["first" + suffix]: "Nicholas",
["last" + suffix]: "Zakas"
};
console.log(person["first name"]); // "Nicholas"
console.log(person["last name"]); // "Zakas"
This is called computed property names
You can achieve this in quite a few different ways.
let foo = {
bar: 'Hello World'
};
foo.bar;
foo['bar'];
The bracket notation is specially powerful as it let's you access a property based on a variable:
let foo = {
bar: 'Hello World'
};
let prop = 'bar';
foo[prop];
This can be extended to looping over every property of an object. This can be seem redundant due to newer JavaScript constructs such as for ... of ..., but helps illustrate a use case:
let foo = {
bar: 'Hello World',
baz: 'How are you doing?',
last: 'Quite alright'
};
for (let prop in foo.getOwnPropertyNames()) {
console.log(foo[prop]);
}
Both dot and bracket notation also work as expected for nested objects:
let foo = {
bar: {
baz: 'Hello World'
}
};
foo.bar.baz;
foo['bar']['baz'];
foo.bar['baz'];
foo['bar'].baz;
Object destructuring
We could also consider object destructuring as a means to access a property in an object, but as follows:
let foo = {
bar: 'Hello World',
baz: 'How are you doing?',
last: 'Quite alright'
};
let prop = 'last';
let { bar, baz, [prop]: customName } = foo;
// bar = 'Hello World'
// baz = 'How are you doing?'
// customName = 'Quite alright'
You can do it like this using Lodash get
_.get(object, 'a[0].b.c');
UPDATED
Accessing root properties in an object is easily achieved with obj[variable], but getting nested complicates things. Not to write already written code I suggest to use lodash.get.
Example
// Accessing root property
var rootProp = 'rootPropert';
_.get(object, rootProp, defaultValue);
// Accessing nested property
var listOfNestedProperties = [var1, var2];
_.get(object, listOfNestedProperties);
Lodash get can be used in different ways, the documentation lodash.get
To access a property dynamically, simply use square brackets [] as follows:
const something = { bar: "Foobar!" };
const userInput = 'bar';
console.log(something[userInput])
The problem
There's a major gotchya in that solution! (I'm surprised other answers have not brought this up yet). Often you only want to access properties that you've put onto that object yourself, you don't want to grab inherited properties.
Here's an illustration of this issue. Here we have an innocent-looking program, but it has a subtle bug - can you spot it?
const agesOfUsers = { sam: 16, sally: 22 }
const username = prompt('Enter a username:')
if (agesOfUsers[username] !== undefined) {
console.log(`${username} is ${agesOfUsers[username]} years old`)
} else {
console.log(`${username} is not found`)
}
When prompted for a username, if you supply "toString" as a username, it'll give you the following message: "toString is function toString() { [native code] } years old". The issue is that agesOfUsers is an object, and as such, automatically inherits certain properties like .toString() from the base Object class. You can look here for a full list of properties that all objects inherit.
Solutions
Use a Map data structure instead. The stored contents of a map don't suffer from prototype issues, so they provide a clean solution to this problem.
const agesOfUsers = new Map()
agesOfUsers.set('sam', 16)
agesOfUsers.set('sally', 2)
console.log(agesOfUsers.get('sam')) // 16
Use an object with a null prototype, instead of the default prototype. You can use Object.create(null) to create such an object. This sort of object does not suffer from these prototype issues, because you've explicitly created it in a way that it does not inherit anything.
const agesOfUsers = Object.create(null)
agesOfUsers.sam = 16
agesOfUsers.sally = 22;
console.log(agesOfUsers['sam']) // 16
console.log(agesOfUsers['toString']) // undefined - toString was not inherited
You can use Object.hasOwn(yourObj, attrName) to first check if the dynamic key you wish to access is directly on the object and not inherited (learn more here). This is a relatively newer feature, so check the compatibility tables before dropping it into your code. Before Object.hasOwn(yourObj, attrName) came around, you would achieve this same effect via Object.prototype.hasOwnProperty.call(yourObj, attrName). Sometimes, you might see code using yourObj.hasOwnProperty(attrName) too, which sometimes works but it has some pitfalls that you can read about here.
// Try entering the property name "toString",
// you'll see it gets handled correctly.
const user = { name: 'sam', age: 16 }
const propName = prompt('Enter a property name:')
if (Object.hasOwn(user, propName)) {
console.log(`${propName} = ${user[propName]}`)
} else {
console.log(`${propName} is not found`)
}
If you know the key you're trying to use will never be the name of an inherited property (e.g. maybe they're numbers, or they all have the same prefix, etc), you can choose to use the original solution.
I came across a case where I thought I wanted to pass the "address" of an object property as data to another function and populate the object (with AJAX), do lookup from address array, and display in that other function. I couldn't use dot notation without doing string acrobatics so I thought an array might be nice to pass instead. I ended-up doing something different anyway, but seemed related to this post.
Here's a sample of a language file object like the one I wanted data from:
const locs = {
"audioPlayer": {
"controls": {
"start": "start",
"stop": "stop"
},
"heading": "Use controls to start and stop audio."
}
}
I wanted to be able to pass an array such as: ["audioPlayer", "controls", "stop"] to access the language text, "stop" in this case.
I created this little function that looks-up the "least specific" (first) address parameter, and reassigns the returned object to itself. Then it is ready to look-up the next-most-specific address parameter if one exists.
function getText(selectionArray, obj) {
selectionArray.forEach(key => {
obj = obj[key];
});
return obj;
}
usage:
/* returns 'stop' */
console.log(getText(["audioPlayer", "controls", "stop"], locs));
/* returns 'use controls to start and stop audio.' */
console.log(getText(["audioPlayer", "heading"], locs));
ES5 // Check Deeply Nested Variables
This simple piece of code can check for deeply nested variable / value existence without having to check each variable along the way...
var getValue = function( s, context ){
return Function.call( context || null, 'return ' + s )();
}
Ex. - a deeply nested array of objects:
a = [
{
b : [
{
a : 1,
b : [
{
c : 1,
d : 2 // we want to check for this
}
]
}
]
}
]
Instead of :
if(a && a[0] && a[0].b && a[0].b[0] && a[0].b[0].b && a[0].b[0].b[0] && a[0].b[0].b[0].d && a[0].b[0].b[0].d == 2 ) // true
We can now :
if( getValue('a[0].b[0].b[0].d') == 2 ) // true
Cheers!
Others have already mentioned 'dot' and 'square' syntaxes so I want to cover accessing functions and sending parameters in a similar fashion.
Code jsfiddle
var obj = {method:function(p1,p2,p3){console.log("method:",arguments)}}
var str = "method('p1', 'p2', 'p3');"
var match = str.match(/^\s*(\S+)\((.*)\);\s*$/);
var func = match[1]
var parameters = match[2].split(',');
for(var i = 0; i < parameters.length; ++i) {
// clean up param begninning
parameters[i] = parameters[i].replace(/^\s*['"]?/,'');
// clean up param end
parameters[i] = parameters[i].replace(/['"]?\s*$/,'');
}
obj[func](parameters); // sends parameters as array
obj[func].apply(this, parameters); // sends parameters as individual values
I asked a question that kinda duplicated on this topic a while back, and after excessive research, and seeing a lot of information missing that should be here, I feel I have something valuable to add to this older post.
Firstly I want to address that there are several ways to obtain the value of a property and store it in a dynamic Variable. The first most popular, and easiest way IMHO would be:
let properyValue = element.style['enter-a-property'];
however I rarely go this route because it doesn't work on property values assigned via style-sheets. To give you an example, I'll demonstrate with a bit of pseudo code.
let elem = document.getElementById('someDiv');
let cssProp = elem.style['width'];
Using the code example above; if the width property of the div element that was stored in the 'elem' variable was styled in a CSS style-sheet, and not styled inside of its HTML tag, you are without a doubt going to get a return value of undefined stored inside of the cssProp variable. The undefined value occurs because in-order to get the correct value, the code written inside a CSS Style-Sheet needs to be computed in-order to get the value, therefore; you must use a method that will compute the value of the property who's value lies within the style-sheet.
Henceforth the getComputedStyle() method!
function getCssProp(){
let ele = document.getElementById("test");
let cssProp = window.getComputedStyle(ele,null).getPropertyValue("width");
}
W3Schools getComputedValue Doc This gives a good example, and lets you play with it, however, this link Mozilla CSS getComputedValue doc talks about the getComputedValue function in detail, and should be read by any aspiring developer who isn't totally clear on this subject.
As a side note, the getComputedValue method only gets, it does not set. This, obviously is a major downside, however there is a method that gets from CSS style-sheets, as well as sets values, though it is not standard Javascript.
The JQuery method...
$(selector).css(property,value)
...does get, and does set. It is what I use, the only downside is you got to know JQuery, but this is honestly one of the very many good reasons that every Javascript Developer should learn JQuery, it just makes life easy, and offers methods, like this one, which is not available with standard Javascript.
Hope this helps someone!!!
For anyone looking to set the value of a nested variable, here is how to do it:
const _ = require('lodash'); //import lodash module
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.set(object, 'a[0].b.c', 4);
console.log(object.a[0].b.c);
// => 4
Documentation: https://lodash.com/docs/4.17.15#set
Also, documentation if you want to get a value: https://lodash.com/docs/4.17.15#get
You can do dynamically access the property of an object using the bracket notation. This would look like this obj[yourKey] however JavaScript objects are really not designed to dynamically updated or read. They are intended to be defined on initialisation.
In case you want to dynamically assign and access key value pairs you should use a map instead.
const yourKey = 'yourKey';
// initialise it with the value
const map1 = new Map([
['yourKey', 'yourValue']
]);
// initialise empty then dynamically assign
const map2 = new Map();
map2.set(yourKey, 'yourValue');
console.log(map1.get(yourKey));
console.log(map2.get(yourKey));
demo object example
let obj = {
name: {
first_name: "Bugs",
last_name: "Founder",
role: "Programmer"
}
}
dotted string key for getting the value of
let key = "name.first_name"
Function
const getValueByDottedKeys = (obj, strKey)=>{
let keys = strKey.split(".")
let value = obj[keys[0]];
for(let i=1;i<keys.length;i++){
value = value[keys[i]]
}
return value
}
Calling getValueByDottedKeys function
value = getValueByDottedKeys(obj, key)
console.log(value)
output
Bugs
const getValueByDottedKeys = (obj, strKey)=>{
let keys = strKey.split(".")
let value = obj[keys[0]];
for(let i=1;i<keys.length;i++){
value = value[keys[i]]
}
return value
}
let obj = {
name: {
first_name: "Bugs",
last_name: "Founder",
role: "Programmer"
}
}
let key = "name.first_name"
value = getValueByDottedKeys(obj, key)
console.log(value)
I bumped into the same problem, but the lodash module is limited when handling nested properties. I wrote a more general solution following the idea of a recursive descendent parser. This solution is available in the following Gist:
Recursive descent object dereferencing
Finding Object by reference without, strings,
Note make sure the object you pass in is cloned , i use cloneDeep from lodash for that
if object looks like
const obj = {data: ['an Object',{person: {name: {first:'nick', last:'gray'} }]
path looks like
const objectPath = ['data',1,'person',name','last']
then call below method and it will return the sub object by path given
const child = findObjectByPath(obj, objectPath)
alert( child) // alerts "last"
const findObjectByPath = (objectIn: any, path: any[]) => {
let obj = objectIn
for (let i = 0; i <= path.length - 1; i++) {
const item = path[i]
// keep going up to the next parent
obj = obj[item] // this is by reference
}
return obj
}
You can use getter in Javascript
getter Docs
Check inside the Object whether the property in question exists,
If it does not exist, take it from the window
const something = {
get: (n) => this.n || something.n || window[n]
};
You should use JSON.parse, take a look at https://www.w3schools.com/js/js_json_parse.asp
const obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}')
console.log(obj.name)
console.log(obj.age)

draggable on ScalaJS removeEventListener does not work

based on that js demo: http://jsfiddle.net/wfbY8/737/
class Draggable(element: HTMLDivElement) {
var offX: Double = 0
var offY: Double = 0
val divMove = (e:MouseEvent) => {
//element.style.position = 'absolute';
element.style.top = (e.clientY-offY) + "px"
element.style.left = (e.clientX-offX) + "px"
}
val mouseDown = (e:MouseEvent) => {
offY = e.clientY - element.offsetTop
offX = e.clientX - element.offsetLeft
window.addEventListener("mousemove", divMove, useCapture = true)
println("added")
}
val mouseUp = (e:MouseEvent) => {
window.removeEventListener("mousemove", divMove, useCapture = true)
println("removed")
}
def addListeners(){
element.addEventListener("mousedown", mouseDown, useCapture = false)
window.addEventListener("mouseup", mouseUp, useCapture = false)
}
addListeners()
}
From the client code I use it like:
val panelElem = document.getElementById(COMPONENT_ID).asInstanceOf[HTMLDivElement]
if (draggable == null) {
draggable = new Draggable(panelElem)
}
I see "added" and "removed" on my log. But the element still movable (when I move mouse without pressing it) for me as if I did not removed mousemove event from the listener (on mouseUp).
I wonder why..
This happens because you're effectively converting the Scala function (the lambda) into a JS function separately for add and remove. In Scala.js, Scala functions are implicitly converted to JS functions as needed. However, the conversion yields a different JS function every time (it does not have the same identity). Therefore, the function you're trying to remove is not the same as the one you added, and of course that has no effect.
You can fix this by forcing the conversion to happen early, so that then you add and remove the same function. To do so, simply add an explicit type to your function vals as JS functions:
val divMove: js.Function1[MouseEvent, Unit] = (e:MouseEvent) => {
...
}
This way, the conversion from Scala function to JS function happens only once, and it is the same JS function that is given to add- and removeEventListener.

Higher order functions not working in casperjs

I have function defined like this
casper.executeRemote = (fn,params)->
->
try
fn.apply(this,params)
catch e
console.log(e)
getLinks = ->
elems = document.querySelectorAll('#pagination-flickr a')
and i am calling the function like below
casper.then ->
all_links = #evaluate #executeRemote getLinks
casper.log all_links,'debug'
However I get the below error when i try to run this in casperjs
ReferenceError: Can't find variable: fn
The same code works fine, if i try in a browser console(compiled js). What is that I am doing wrong?
Of course they work, but not at the border to the page context:
Note: The arguments and the return value to the evaluate function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine.
Closures, functions, DOM nodes, etc. will not work!
Thankfully there is the toString function on Functions. So, you can change your code a little to account for passing the function as a string and evaling inside of the page context.
(Untested) example:
casper.executeRemote = (fn,params)->
fn = eval('('+fn+')')
try
fn.apply(this,params)
catch e
console.log(e)
getLinks = ->
elems = document.querySelectorAll('#pagination-flickr a')
casper.then ->
all_links = #evaluate(#executeRemote, getLinks.toString())
casper.log all_links,'debug'
Based on #Artjom's answer. I modified the code as shown below, then it works
executeRemote = (fn,params)->
->
try
fn.apply(this,params)
catch e
console.log(e)
getLinks = ->
elems = document.querySelectorAll('#pagination-flickr a')
links = (link.href for link in elems)
remoteWrapper = (excRm,gL)->
excRm=eval('('+excRm+')')
gL=eval('('+gL+')')
fn=excRm(gL)
fn()
casper.on 'remote.message',(message)->
#echo message
casper.then ->
all_links = #evaluate remoteWrapper, executeRemote.toString(), getLinks.toString()
casper.log all_links,'debug'

"this" in a prototype method does not always refer to the prototype of the object itself?

Most of the times all I have to do with JavaScript is just add some dynamics to simple HTML. Recently, however, after discovering CoffeeScript, I got interested in *Object Oriented JavaScript". Here is some code in CoffeeScript.
class MyClass
constructor: (title, purpose)->
#title = typeof title is undefined ? "My Class" : title
#purpose = typeof purpose is undefined ? "None" : purpose
#myMethod()
myMethod: ->
_getTitle = #getTitle
_getPurpose = #getPurpose
$(window).click ->
_getTitle()
_getPurpose()
return
return
getTitle: ->
_title = #title
window.console.log "Title of the class this object belongs to is: #{_title}"
return
getPurpose: ->
_purpose = #purpose
window.console.log "Purpose of creating this class is: #{_purpose}"
return
title = ""
purpose = ""
myObject = new MyClass("Testbed", "to test Object Oriented JavaScript")
For those who prefer JavaScript, here is the compiled (?) JavaScript.
var MyClass, myObject;
MyClass = (function() {
var purpose, title;
function MyClass(title, purpose) {
var _ref, _ref1;
this.title = (_ref = typeof title === void 0) != null ? _ref : {
"My Class": title
};
this.purpose = (_ref1 = typeof purpose === void 0) != null ? _ref1 : {
"None": purpose
};
this.myMethod();
}
MyClass.prototype.myMethod = function() {
var _getPurpose, _getTitle;
_getTitle = this.getTitle;
_getPurpose = this.getPurpose;
$(window).click(function() {
_getTitle();
_getPurpose();
});
};
MyClass.prototype.getTitle = function() {
var _title;
_title = this.title;
window.console.log("Title of the class this object belongs to is: " + _title);
};
MyClass.prototype.getPurpose = function() {
var _purpose;
_purpose = this.purpose;
window.console.log("Purpose of creating this class is: " + _purpose);
};
title = "";
purpose = "";
return MyClass;
})();
myObject = new MyClass("Testbed", "to test Object Oriented JavaScript");
Sorry about the long code. I had to try to keep it interesting. The thing is, this code outputs:
Title of the class this object belongs to is: undefined
Purpose of creating this class is: undefined
whereas I was expecting it to output:
Title of the class this object belongs to is: Testbed
Purpose of creating this class is: to test Object Oriented JavaScript
And I could've sworn this was how it worked when I last tinkered with it (around six months ago). I learnt that in a method that is part of the prototype of an object, this refers to the prototype itself. And this.something would actually point to object.something. Whereas in this example, inside myObject.myMethod(), this behaves as it should and this.getTitle() refers to myObject.getTitle(). Inside myObject.getTitle(), however, this refers to window. Why?
Is it because getTitle() was called inside a $(window).click() handler? But why would that change the context? getTitle() is still a property of myObject.
Also, you see what I am trying to accomplish here. How could I accomplish that?
There are several problems.
1) You never return anything from .getPurpose or .getTitle
2) You should create a reference to this in myMethod. i.e. var me = this and then inside the event listener call me.getTitle() and me.getPurpose(). This is needed because inside the event listener (window onclick), this refers to the window and not the object.
3) It looks like your ternary expressions are always evaluating to false. You need to rethink them.
P.S. I looked at the straight JS version

Calling class function within a constructor isn't being recognised

Answer:
It turns out I had neglected to use the new keyword when creating the class instance. The code in the question itself is fine.
Question:
I have a fairly simple class where the constructor calls another method on the class (editor_for_node). The call happens inside a jQuery each() loop, but I've also tried moving it outside.
define ['jquery'], ($) ->
class Editor
constructor: (#node, #data, #template) ->
#node.widgets().each (i, elem) =>
data = if #data then #data[i] else null
node = $(elem)
#editor_for_node node, data
editor_for_node: (node, data) ->
console.log 'hello!'
return {
'Editor': Editor,
}
When the line #editor_for_node node, data gets called, I get an error (in Firebug) saying this.editor_for_node is not a function.
I really can't see why this isn't working properly, the only possible source of weirdness that I can see is my use of require.js's define function at the start.
Edit: Generated output
(function() {
define(['jquery'], function($) {
var Editor;
Editor = (function() {
Editor.name = 'Editor';
function Editor(node, data, template) {
var _this = this;
this.node = node;
this.data = data;
this.template = template;
this.node.widgets().each(function(i, elem) {
data = _this.data ? _this.data[i] : null;
node = $(elem);
return _this.editor_for_node(node, data);
});
}
Editor.prototype.editor_for_node = function(node, data) {
return console.log('hello!');
};
return Editor;
})();
return {
'Editor': Editor
};
});
}).call(this);
First: Which version of CoffeeScript are you using? The fat arrow has been a source of bugs in certain previous releases.
If you're using the latest (1.3.1), then I'm going to go ahead and say that this is an indentation issue. When I copy and paste your code, it works fine. Are you mixing tabs and spaces? Verify that the compiled output contains the line
Editor.prototype.editor_for_node = ...
Update: See the comments on this answer. Turns out the problem was that the new keyword wasn't being used when invoking the constructor.