How to write this function in coffeescript - coffeescript

I am struggling to re-produce a function like this in coffeescript could someone help me out a little.
// Listen to message from child window
eventer(messageEvent,function(e) {
console.log('parent received message!: ',e.data);
},false);

Your code translates to this equivalent one in CoffeeScript:
# Listen to message from child window
eventer messageEvent, ((e) ->
console.log "parent received message!: ", e.data
), false
You can always use this tool in the future if you need help with the CoffeeScript equivalence of a JavaScript code:
http://js2coffee.org/

# Listen to message from child window
eventer messageEvent, (e) ->
console.log "parent received message!: #{e.data}"
, false
Verified with coffeescript.org's sandbox CoffeeScript compiler.

Related

how to get 'on' event listener in ibm-cloud/cloudant package?

The deprecated #cloudant/cloudant is replaced by ibm-cloud/cloudant package. In former I was using following code snippet
const feed = dummyDB.follow({ include_docs: true, since: 'now'})
feed.on('change', function (change) {
console.log(change)
})
feed.on('error', function (err) {
console.log(err)
})
feed.filter = function (doc, req) {
if (doc._deleted || doc.clusterId === clusterID) {
return true
}
return false
}
Could you share a code for which I can get feed.on event listener similar to above code in new npm package ibm-cloud/cloudant.
There isn't an event emitter for changes in the #ibm-cloud/cloudant package right now. You can emulate the behaviour by either:
polling postChanges (updating the since value after new results) and processing the response result property, which is a ChangesResult. That in turn has a results property that is an array of ChangesResultItem elements, each of which is equivalent to the change argument of the event handler function.
or
call postChangesAsStream with a feed type of continuous and process the stream returned in the response result property, each line of which is a JSON object that follows the structure of ChangesResultItem. In this case you'd also probably want to configure a heartbeat and timeouts.
In both cases you'd need to handle errors to reconnect in the event of network glitches etc.

Atom package - setInterval not calling the function

I'm currently working on a package for atom which involves drawing a curve on a canvas. For whatever reason the following code logs "mouseDown" without ever logging "hi" when handleClickDown is called. I've tried without window. but still "mouseDown" is all that's logged. The handleClickDown function is called every time the canvas is clicked if that context helps at all. I'm sure I'm just not understanding something about how setInterval / coffescript works since I'm new to both atom and coffescript. Any help is appreciated.
#printhi: ->
console.log "hi"
handleClickDown: (event, element) ->
console.log "mouseDown"
#mouseDownId = window.setInterval(#printhi,100)
Edit: The following code seems to run fine
console.log "mouseDown"
#mouseDownId = setInterval(()=>
console.log "inner"
,75)
however when using a function like this it throws an error that _this.printhi is not a function
#printhi = () ->
console.log "hi"
handleClickDown: (event, element) ->
console.log "mouseDown"
#mouseDownId = setInterval(()=>
#printhi()
,75)
Ok just answering my own question here as I figured it out eventually. Turns out I was a bit confused on how # and => work in coffeescript. You actually need to remove the # from #printhi: -> so it becomes printhi: -> and then only use it when you're calling it like this #printhi().
Code below worked for me, hope someone finds this helpful
printhi: ->
console.log "hi"
handleClickDown: (event, element) ->
console.log "mouseDown"
#mouseDownId = setInterval(()=>
#printhi()
,75)

What is the use of boost::asio::async_write function

Can anyone please help me with this code , what is the use of "boost::asio::async_write" function here
Does it sends acknowledgment back to the client ?
void handle_read(const boost::system::error_code& error,
size_t bytes_transferred)
{
if (!error)
{
boost::asio::async_write(socket_,
boost::asio::buffer(data_, bytes_transferred),
boost::bind(&session::handle_write, this,
boost::asio::placeholders::error));
}
else
{
delete this;
}
}
It looks like this is from an "echo server" example. async_write writes the contents of boost::asio::buffer(data_, bytes_transferred) to the socket.
Since we're inside handle_read we can guess that this function itself is the completion handler for a likely async_read call that filled that data_ buffer. Since we use the exact number of bytes reported back by async_read (bytes_transferred) and there's no visible manipulation on data_, we can assume that this simply sends the exact message (or data in general) received to socket_. If socket_ was also the endpoint in the async_read this is the definition of an echo server.

Docpad: using extendTemplateData via mongoose callback

I'm trying to build a simple plugin to get get data from Mongo into an object over which I can iterate when rendering. The full code is in my project, but the essence of it is a failed attempt to emulate the feedr example. I know the mongoose stuff is working as the console log works, but getting the content sent to the docpad object is defeating me
class mongoPlugin extends BasePlugin
name: 'mongo'
# Fetch list of Gigs
getGigsData: (opts) ->
mongoose.connect ('mongodb://localhost/test')
db = mongoose.connection;
db.on 'error', console.error.bind(console, 'connection error:')
db.once 'open', () ->
gigsSchema = mongoose.Schema {
date : String,
location : String
}
Gigs = mongoose.model 'Gigs', gigsSchema
Gigs.find {}, (err, gigs) ->
mongoose.connection.close()
if err then console.error "db error"
else
console.dir gigs
opts["getGigsData"] = gigs
opts.templateData["getGigsData"] = gigs
return gigs
extendTemplateData: (opts) ->
opts.templateData["getGigsData"] = #getGigsData()
Using node-inspector and triggering a regeneration by editing docpad.coffee, I can see that opts has a field templateData, but it is empty, and is very different from docpad.templateData, so I am picking up the wrong object in the plugin. I can see others did a trick of placing a name in { } but I don't know what that does.
After completing the plugin code I see that my database data becomes the argument to a promise, so perhaps that's where it is supposed to be reintegrated with the docpad.config.templateData but that does not seem to happen in practise
So the main issue here is that we have an asynchronous function getGetsData being executed inside a synchronous function, your templating engine. This simply, isn't possible, as the templating engine will go on and do its thing, while the synchronous stuff happens in the background. This is just an issue with just writing node.js/asynchronous code in general.
The fixes for this is pretty easy to do.
opts.templateData["getGigsData"] = #getGigsData() calls getGigsData without passing over the opts, so that when getGigsData tries and uses the opts, it can't, so that would throw an error. The fix for this is to do #getGigsData(opts)
opts.templateData["getGigsData"] = #getGigsData(opts) assigns the return value of #getGigsData(opts) to the template data, however, the result of this is the result of the db.once call, as that is what will be returned in that scope. When you do return gigs, that's actually the return value for the (err, gigs) -> callback on the Gigs.find call, rather than the return value for the getGigsData. It's all about scopes.
As the database stuff is asynchronous, we need to make getGigsData asynchronous. To do this, we change extendTemplateData: (opts) -> to extendTemplateData: (opts,next) -> to make it asynchronous, and change opts.templateData["getGigsData"] = #getGigsData() to simply return #getGigsData(opts,next)
Now that we have the event and call asynchronous. We now need to make the definition of getGigsData support it. So lets change getGigsData: (opts) -> to getGigsData: (opts,next) -> to take in the completion callback (next) that we defined in step 3. And what we will do, is we will call next where we have return gigs, so lets change return gigs to return next()
It should now work. But as a little bit of cleaning, we can make the error handling better by changing if err then console.error "db error" to return next(err) if err. You will need to fix up the indentation as we will need to remove the else block.
Considering all that, and with a bit more cleaning applied, you'll end up with this:
class mongoPlugin extends BasePlugin
name: 'mongo'
config:
hostname: 'mongodb://localhost/test'
# Fetch list of Gigs
getGigsData: (opts={}, next) ->
config = #getConfig()
docpad = #docpad
mongoose.connect(config.hostname)
db = mongoose.connection
db.on 'error', (err) ->
docpad.error(err) # you may want to change this to `return next(err)`
db.once 'open', ->
gigsSchema = mongoose.Schema {
date: String,
location: String
}
Gigs = mongoose.model('Gigs', gigsSchema)
Gigs.find {}, (err, gigs) ->
mongoose.connection.close()
return next(err) if err
return next(null, gigs)
# Chain
#
extendTemplateData: (opts,next) ->
#getGigsData null, (err, gigs) ->
return next(err) if err
opts.templateData.gigs = gigs
# Chain
#

Nodejs streaming

I want to realize a simple client-server connection using Nodejs.
But I've encountered with the following problem.
Consider the code
server.js:
var net = require('net'),
sys = require('sys');
net.createServer(onConnection).listen(8124);
function onConnection(socket) {
socket.setNoDelay(true);
socket.addListener("connect", function () {
sys.puts('client connected: ' + this.remoteAddress);
});
socket.addListener("data", function (data) {
sys.puts("message: \n" + data + "\n - end of msg.");
});
socket.addListener("end", function () {
sys.puts('end of connection');
this.end();
});
}
sys.puts('Server running at 127.0.0.1:8124');
client.js:
var net = require('net'),
sys = require('sys');
var stream = net.createConnection(8124);
stream.addListener("connect", function(){
sys.puts('connected');
stream.write('a');
stream.flush();
stream.write('b');
stream.flush();
});
stream.addListener("data", function(data){
sys.puts("Message: \n" + data + "\n - end of msg.");
});
When I run client.js I sometimes get only one message 'ab' instead of two messages 'a' and 'b'.
Is there some 'right method' to deal with that?
TCP is a stream protocol. Single write on one end of the pipe can result in multiple "reads" on the other end, and the other way around. You have to either explicitly tell the other side how many bytes you are sending by including the length in the message; or provide easily recognizable message delimiters. In any case you need to read in a loop.
use socket.write return value and callback as documented here https://nodejs.org/api/net.html#net_socket_write_data_encoding_callback to know when the data is completly flushed to the kernel . Wait for that to happen and after that call the second write. that way you make sure of the ordering. Regarding the problem of logic separartion of "a" and "b" you might want to design/implement that "protocol yourself, it's not a responsiblity of the (low-level) socket API.
FYI, if you are able to structure to be a line-based text protocol, you can use readline. See:
https://nodejs.org/api/readline.html#example-tiny-cli
https://nodejs.org/api/readline.html#example-read-file-stream-line-by-line