Calling class function within a constructor isn't being recognised - coffeescript

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.

Related

How to see the value of a top level empty getter without running the code in Swift?

public var O_RDONLY: Int32 { get }
When I'm looking at stuff inside Darwin.sys.* or Darwin.POSIX.* for example, a lot of these constants are defined as getters. But how does one see the actual value without evaluating the code?
public var O_RDONLY: Int32 { get }
is what the Swift importer generates from the macro definition
#define O_RDONLY 0x0000 /* open for reading only */
in the <sys/fcntl.h> include file. Although this is a fixed value, known at compile time, the Swift importer does not show the value in the generated Swift interface.
Note also that a macro definition in a C header file may depend on other macros, and on other “variables” such as compiler flags, the processor architecture, etc.
I am not aware of a way to navigate to that C definition from a Swift file, or any other way to show the defined value in a pure Swift project. As a workaround, one can
add a C file to the project,
use the macro in some C function, and
“jump to definition” from there.
I ended up with the following solution:
const fs = require('fs');
const { exec } = require("child_process");
const getterRegEx = /^(.*)public var (.+): (.+) { get }(.*)$/;
const code = String(fs.readFileSync('./generatedSwift.swift'));
const lines = code.split('\n').map((line, i) => {
const arr = getterRegEx.exec(line);
if (arr) {
const [all, prefix, constant, type, suffix] = arr;
return `print("let ${constant}: ${type} = ", ${constant}, separator: "")`;
}
return `print("""\n${line}\n""")`;
});
lines.unshift('import Foundation');
fs.writeFileSync('./regeneratedSwift.swift', lines.join('\n'));
exec('swift ./regeneratedSwift.swift', (err, stdout, stderr) => {
if (err) {
console.error(`exec error: ${err}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return;
}
console.log(`stdout: ${stdout}`);
});
Copy definitions generated by the XCode and save into a file named generatedSwift.swift the run node index.js in the same folder.
The output will contain the Swift code where all
public var Constant: Type { get }
are replaced with
let Constant = Value
and all other lines will remain the same.

jsTree customize <li> using the alternative JSON format along with AJAX

I am using the alternative JSON format along with AJAX to load data in tree. Now there is a new ask, I am required to add a new element at the end of <li> tag.
I have created sample URL to display what I am currently doing.
Tree crated using alternative JSON format along with AJAX
And how the new LI should appear
Tree created using hard coded HTML but shows how the LI should look like
I think I should be able to do this if I use HTML Data but since the project is already live with JSON format this would require me to change a lot so before I start making this major change I just wanted to check if this is possible using JSON and AJAX format or not.
So I got answer from Ivan - Answer
In short there is misc.js in the src folder which has question mark plugin, this is the best example of what I wanted to do.
I tweaked its code for my needs and here is the new code.
(function ($, undefined) {
"use strict";
var span = document.createElement('span');
span.className = 'glyphicons glyphicons-comments flip jstree-comment'
$.jstree.defaults.commenticon = $.noop;
$.jstree.plugins.commenticon = function (options, parent) {
this.bind = function () {
parent.bind.call(this);
};
this.teardown = function () {
if (this.settings.commenticon) {
this.element.find(".jstree-comment").remove();
}
parent.teardown.call(this);
};
this.redraw_node = function (obj, deep, callback, force_draw) {
var addCommentIcon = true;
var data = this.get_node(obj).data;
//....Code for deciding whether comment icon is needed or not based on "data"
var li = parent.redraw_node.call(this, obj, deep, callback, force_draw);
if (li && addCommentIcon) {
var tmp = span.cloneNode(true);
tmp.id = li.id + "_commenticon";
var $a = $("a", li);
$a.append(tmp);
}
return li;
};
};
})(jQuery);

Access to the elements of the page in the Page-Worker

I've created a page-worker in the extension
dup = pageWorker.Page({
contentScript: "self.port.on('alert', function(message) {"+
"console.log(message);"+
"document.querySelector('.test-element').title = message;"+
"});",
contentScriptWhen: "ready",
contentURL: "http://example.com/Licznik-beta/addon.html"
});
In "contentScript" I can relate to "document".
But I can not relate to the window, or function, or variable.
console.log(window) in contentScript return "TypeError: cyclic object value timers.js:43".
I do not understand how it works.
Can someone explain to me?
How to change it?
EDIT
I've added a few lines to the test:
self.port.on('addon-licznik', function () {
console.log(document);
console.log(window); // TypeError: cyclic object value timers.js:43
runFromAddon(); // ReferenceError: runFromAddon is not defined timers.js:43
});
Function: runFromAddon(); Of course there is.
Second test:
function funSet (tresc) {
var addonScript = document.querySelector(".addon-script");
if ( addonScript != undefined ) {
document.querySelector('head').removeChild( addonScript );
}
var script = document.createElement("script");
script.className = "addon-script";
script.textContent = tresc;
document.querySelector('head').appendChild(script);
}
function marmo (message) {
console.log(message);
funSet("console.log(window); runFromAddon();");
}
self.port.on('addon-licznik', marmo);
It works well.
Window → http://example.com/Licznik-beta/addon.html
runFromAddon-Log
If you're writing the HTML yourself, then use addon instead of self and attach the script to the page using <script></script> instead of contentScript(File). See Scripting trusted page content.
If you're not writing the HTML, then see Communicating with Page Scripts.

"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

tinymce.dom.replace throws an exception concerning parentNode

I'm writing a tinyMce plugin which contains a section of code, replacing one element for another. I'm using the editor's dom instance to create the node I want to insert, and I'm using the same instance to do the replacement.
My code is as follows:
var nodeData =
{
"data-widgetId": data.widget.widgetKey(),
"data-instanceKey": "instance1",
src: "/content/images/icon48/cog.png",
class: "widgetPlaceholder",
title: data.widget.getInfo().name
};
var nodeToInsert = ed.dom.create("img", nodeData);
// Insert this content into the editor window
if (data.mode == 'add') {
tinymce.DOM.add(ed.getBody(), nodeToInsert);
}
else if (data.mode == 'edit' && data.selected != null) {
var instanceKey = $(data.selected).attr("data-instancekey");
var elementToReplace = tinymce.DOM.select("[data-instancekey=" + instanceKey + "]");
if (elementToReplace.length === 1) {
ed.dom.replace(elementToReplace[0], nodeToInsert);
}
else {
throw new "No element to replace with that instance key";
}
}
TinyMCE breaks during the replace, here:
replace : function(n, o, k) {
var t = this;
if (is(o, 'array'))
n = n.cloneNode(true);
return t.run(o, function(o) {
if (k) {
each(tinymce.grep(o.childNodes), function(c) {
n.appendChild(c);
});
}
return o.parentNode.replaceChild(n, o);
});
},
..with the error Cannot call method 'replaceChild' of null.
I've verified that the two argument's being passed into replace() are not null and that their parentNode fields are instantiated. I've also taken care to make sure that the elements are being created and replace using the same document instance (I understand I.E has an issue with this).
I've done all this development in Google Chrome, but I receive the same errors in Firefox 4 and IE8 also. Has anyone else come across this?
Thanks in advance
As it turns out, I was simply passing in the arguments in the wrong order. I should have been passing the node I wanted to insert first, and the node I wanted to replace second.