.bind(this) in coffee-react [duplicate] - coffeescript

This question already has an answer here:
.bind function with CoffeeScript [duplicate]
(1 answer)
Closed 7 years ago.
I'm using the qwest library for load data from server.
Originally, I wrote:
qwest.get("/api/getData")
.then(function(response){
this.setState({data: response})
}.bind(this))
And this works fine.
In coffeescript I wrote:
qwest.get("/api/getData")
.then (response) ->
this.setState({data: response})
.bind(this)
And this doesn't work.
I'm sure the problem lies in .bind(this), because it will compile to:
qwest.get("/api/getData")
.then(function(response) {
return this.setState({
conf: response
});
}).bind(this);
but .bind() is not in front of a curly brace.
How can I fix this?

Just add some parentheses around the (response) -> ...:
qwest.get("/api/getData")
.then ((response) ->
this.setState({data: response})
).bind(this)
which compiles to
qwest.get("/api/getData").then(function(response) {
return this.setState({data: response});
}.bind(this));
Which is the desired effect.

Related

How to rewrite closing current tab function with "async/await" instead of ".then"?

For closing current tab in my test I use next function:
browser.getAllWindowHandles().then((handles) => {
browser.driver.switchTo().window(handles[1]);
browser.driver.close();
browser.driver.switchTo().window(handles[0]);
});
And it works good. But I must rewrite to "async/await" instead of ".then". I try next code:
async function goBackToPreviousTab () {
let handles = await browser.getAllWindowHandles();
browser.driver.switchTo().window(handles[1]);
browser.driver.close();
browser.driver.switchTo().window(handles[0]);
}
but in result receive next error:
no such window: target window already closed
from unknown error: web view not found
First of all, understand that .then or await is a way of resolving Promises. So whatever returns a promise needs to be explicitly resolved. For example, .close() returns a Promise too, and needs either of the syntax
This is why, back your question, your function should be
async function goBackToPreviousTab () {
let handles = await browser.getAllWindowHandles();
await browser.driver.switchTo().window(handles[1]);
await browser.driver.close();
await browser.driver.switchTo().window(handles[0]);
}
because each of your commands is a Promise

Sails.js: error logging in with passport

When this part of my code gets executed:
req.login(user, function (err){
if (err) return res.negotiate(err);
return res.redirect('/welcome');
});
I get the following error:
/home/oriol/Desktop/containers/node_modules/sails-mongo/node_modules/mongodb/lib/utils.js:98
process.nextTick(function() { throw err; });
^
Error: passport.initialize() middleware not in use
at IncomingMessage.req.login.req.logIn (/home/oriol/Desktop/containers/node_modules/passport-local/node_modules/passport/lib/passport/http/request.js:30:30)
at /home/oriol/Desktop/containers/api/controllers/AuthController.js:37:15
at wrapper (/home/oriol/Desktop/containers/node_modules/lodash/index.js:3592:19)
at applyInOriginalCtx (/home/oriol/Desktop/containers/node_modules/waterline/lib/waterline/utils/normalize.js:421:80)
at wrappedCallback (/home/oriol/Desktop/containers/node_modules/waterline/lib/waterline/utils/normalize.js:324:18)
at success (/home/oriol/Desktop/containers/node_modules/waterline/node_modules/switchback/lib/normalize.js:33:31)
at _switch (/home/oriol/Desktop/containers/node_modules/waterline/node_modules/switchback/lib/factory.js:58:28)
at /home/oriol/Desktop/containers/node_modules/waterline/lib/waterline/query/dql/create.js:248:9
at /home/oriol/Desktop/containers/node_modules/async/lib/async.js:52:16
at /home/oriol/Desktop/containers/node_modules/async/lib/async.js:269:32
at /home/oriol/Desktop/containers/node_modules/async/lib/async.js:44:16
at child.<anonymous> (/home/oriol/Desktop/containers/node_modules/waterline/lib/waterline/utils/schema.js:152:44)
at fn (/home/oriol/Desktop/containers/node_modules/waterline/lib/waterline/utils/callbacksRunner.js:60:10)
at /home/oriol/Desktop/containers/node_modules/async/lib/async.js:181:20
at iterate (/home/oriol/Desktop/containers/node_modules/async/lib/async.js:262:13)
at Object.async.forEachOfSeries.async.eachOfSeries (/home/oriol/Desktop/containers/node_modules/async/lib/async.js:281:9)
at Object.async.forEachSeries.async.eachSeries (/home/oriol/Desktop/containers/node_modules/async/lib/async.js:214:22)
at Object.runner.afterCreate (/home/oriol/Desktop/containers/node_modules/waterline/lib/waterline/utils/callbacksRunner.js:63:9)
at after (/home/oriol/Desktop/containers/node_modules/waterline/lib/waterline/query/dql/create.js:243:17)
at /home/oriol/Desktop/containers/node_modules/waterline/lib/waterline/query/dql/create.js:230:68
at wrapper (/home/oriol/Desktop/containers/node_modules/lodash/index.js:3592:19)
at applyInOriginalCtx (/home/oriol/Desktop/containers/node_modules/waterline/lib/waterline/utils/normalize.js:421:80)
I have read other posts about the same issue but none of them seems to fix it. I don't know much about why is this happening, feel free to ask for further explanation or any piece of code that might be relevant. Thanks!
I just found out now how to solve that. This question can be closed.
I did this for the second time and somehow it worked: Sails.js + Passport.js: passport.initialize() middleware not in use.

Coffeescript and jQuery chaining

I'm attempting this in coffeescript:
$( element ).mousedown( aFunction ).mouseup( anotherFunction );
I'm trying to work out a way to make use of indents so that something like the following will return what's about:
$ element
.mousedown aFunction
.mouseup anotherFunction
But to no avail, are there any recommendations for chaining in coffeescript?
I'm sure you don't want to use parenthesis, but...
$("#element")
.mousedown(aFunction)
.mouseup(anotherFunction)
Compiles to
$("#element").mousedown(aFunction).mouseup(anotherFunction);
For all the other quick readers out there, here's the updated answer by a paid nerd given here.
req = $.get('foo.html')
.success (response) ->
do_something()
.error (response) ->
do_something()
...compiles to:
var req;
req = $.get('foo.html').success(function(response) {
return do_something();
}).error(function(response) {
return do_something();
});
Looks like mus is too short suggested it in a comment above as well.

Jasmine spyOn with CoffeeScript on Rails 3.1 with test_track

I'm using Jasmine with CoffeeScript (in Rails 3.1) and test_track. Everything else is fine, but I cant have spyOn on function calls to work:
describe "spyOn", ->
it "should spy", ->
foo =
bar: ->
spyOn(foo, 'bar')
foo.bar()
expect(foo.bar).toHaveBeenCalled()
the expect fails. What's wrong?
Update: the same exact code works on tryjasmine. It could be a bug with the version of jasmine with test_track.
For those who got the same problem, here's the answer:
https://github.com/quickleft/test_track/issues/7#issuecomment-2570580
Have a look at the compiled JavaScript and debug from there. Perhaps those returns are causing problems?
describe("spyOn", function() {
return it("should spy", function() {
var foo;
foo = {
bar: function() {}
};
spyOn(foo, 'bar');
foo.bar();
return expect(foo.bar).toHaveBeenCalled();
});
});

How to handle the response in callback functions (used by cradle in nodejs for example)

I'm using "express" and "cradle" in "nodejs". If I request my database I have to define a callback to handle the response. Unfortunately I have no access to res (response) in my callback function. What is the best practice for this problem? Here is my code.
var cradle = require('cradle');
var db = new cradle.Connection().database('guestbook');
app.get('/guestbook', function(req, res) {
db.view('guestbook/all', function(err, doc) {
console.log(doc);
// How can I use res in this callback
// to send the response?
});
});
You can just use res inside the inner callback.
In JavaScript the inner function "inherits" the variables of the outer function. Or more precisely, the function forms a closure, which is an expression that can have free variables. The closure binds the variables from its outer scope, which can be the scope of another function or the global scope.
You may try this.
Most important (perhaps your pitfall?) keep in mind that 'db.view' will mereley register a callback closure and continue. Do not close your request (by calling 'req.end') anywhere outside this closure. If you do, quite likely the request have been closed as the db returns. Once the http response object is closed any data written to it goes void.
var cradle = require('cradle');
var db = new cradle.Connection().database('guestbook');
app.get('/guestbook', function(req, res) {
// Register callback and continue..
db.view('guestbook/all', function(err, guests) {
// console.log('The waiting had an end.. here are the results');
guests.forEach(function(guest) {
if (guest.name) {
res.write('Guest N: ' + guest.name);
}
});
// Close http response (after this no more output is possible).
res.end('That is all!')
});
console.log('Waiting for couch to return guests..');
// res.end('That is all!'); // DO NOT DO THIS!!!
});
With this snippet you really should have access to res here. You should be able to use res.render() or res.send() because the db callback is wrapped in the closure of the app.get callback function.