Is there a way to avoid using 'call' in Coffeescript? - function

I'm writing a simple Twitter client to play with coffeescript. I have an object literal with some functions that call each other via callbacks.
somebject =
foo: 'bar'
authenticateAndGetTweets: ->
console.log "Authorizing using oauth"
oauth = ChromeExOAuth.initBackgroundPage(this.oauthdetails)
oauth.authorize( this.afterLogin.call this )
afterLogin: ->
this.getTweets(this.pollinterval)
This code works perfectly. Edit: actually this.afterlogin should be sent as a callback above, not ran immediately, as Trevor noted below.
If, within authenticateAndGetTweets, I removed the 'call' and just ran:
oauth.authorize( this.afterLogin )
and don't use 'call', I get the following error:
Uncaught TypeError: Object [object DOMWindow] has no method 'getTweets
Which makes sense, since 'this' in afterLogin is bound to the thing that initiated the callback rather than 'someobject' my object literal.
I was wondering if there's some magic in Coffeescript I could be doing instead of 'call'. Initially I thought using the '=>' but the code will give the same error as above if '=>' is used.
So is there a way I can avoid using call? Or does coffeescript not obviate the need for it? What made '=>' not work how I expected it to?
Thanks. I'm really enjoying coffeescript so far and want to make sure I'm doing things 'the right way'.

As matyr points out in his comments, the line
oauth.authorize( this.afterLogin.call this )
doesn't cause this.afterLogin to be called as a callback by oauth.authorize; instead, it's equivalent to
oauth.authorize this.afterLogin()
Assuming that you want this.afterLogin to used as a callback by oauth.authorize, megakorre's answer gives a correct CoffeeScript idiom. An alternative approach supported by many modern JS environments, as matyr points out, would be to write
oauth.authorize( this.afterLogin.bind this )
There's no CoffeeScript shorthand for this, partly because Function::bind isn't supported by all major browsers. You could also use the bind function from a library like Underscore.js:
oauth.authorize( _.bind this.afterLogin, this )
Finally, if you were to define someobject as a class instead, you could use => to define afterLogin such that it's always bound to the instance, e.g.
class SomeClass
foo: 'bar'
authenticateAndGetTweets: ->
console.log "Authorizing using oauth"
oauth = ChromeExOAuth.initBackgroundPage(this.oauthdetails)
oauth.authorize(this.afterLogin)
afterLogin: =>
this.getTweets(this.pollinterval)
someobject = new SomeClass

you can put a lambda in the function call like so
auth.authorize(=> #afterLogin())

You have to use either the call or apply methods because they set the scope of the function (the value of this). The error results because the default scope is the window object.

Related

What does the following warning mean: 'side-effecting nullary methods are discouraged'?

I have a lot of nullary methods (methods with 0 parameters) in my scala test file. Hence, instead of writing them as :
def fooBar() = //
I write them as :
def fooBar = //
I get the following warning when I do so:
Warning:(22, 7) side-effecting nullary methods are discouraged: suggest defining as `def fooBar()` instead
What is the meaning of the warning? I am using intelliJ as my IDE and could not really find much about this warning on the web.
EDIT
And, I forgot to mention, when I use the brackets, the warning does not appear.
The common convention for nullary methods is to:
in case it's a side-effecting method, signify it with use of parenthesis
otherwise, drop parenthesis in case it's pure accessor-like method with no side effects
You're breaking this rule and IDE warns you about this.
See also https://stackoverflow.com/a/7606214/298389
Does fooBar have side-effects?
It's simply stating a good practice to define a side-effecting method as such:
def fooBar() = ...
And non-side-effecting methods like this:
def fooBar = ...
Since the method call looks similar to accessing a val, it's good to differentiate when the method is doing more than just returning a value.

Reference to "this" changed inside Sortables Class

I was testing Jakobs patch on the Sortables Class and this line this.reset() gave me a Uncaught TypeError: undefined is not a function.
I don't understand why since the Class has a method reset.
So my solution was to a var self = this; inside the same end: method (here), and called self.reset(); in the same line as I had this.reset(); before. Worked good. Why?
Then just to check (I suspected already) I did a console.log(this == self) and gave false.
Why does using self work but not this?
Fiddle
In javascript the this keyword change accordingly with the execution context
in global code this refer to the global object
inside eval the scope is the same as the calling context one, if no context provided then is the same as above
in all the case below if the this argument passed to .bind .call or .apply is not an object (or null) this will be the global object
when using a function which has been binded to a specific object using .bind then this refers to the this argument passed to bind, the function is now permabinded.
when running a function the context is provided from the caller, if before the function call operator () there is a dot(.) or a [] operator then this refers to the part on the left of such operator, unless the function is permabinded to something else or we are using .call or .apply if so this refers to the this argument unless the function was previously permabinded;
if before the function call operator () there neither the . nor the [] operators then this will refer to the global object (unless the function stores the result of the .bind function)
when running a constructor function (basically when using new) this refers to the object we are creating
now when using the use strict directive things changes a bit, mostly instead of the global object when the context is not given this will be null, but not in all the cases.
I rarely use "use strict" so I just suggest to try it by yourself when in need.
now, what happens when a function is cached inside a variable like this:
var cache = 'A.foo'
if that you lose the context in which the original function was stored, so in this case foo will not be anymore a property on the instance A and when you run it using
cache()
the context will be evaluated using the rules I wrote above in this case the this will refer to the global object.
The semantics of "this" in Javascript are not what is expected by OO programmers. The symbol "this" refers to the dynamic/runtime calling context, not the lexicographic context. For example, if you have an object A with "method" and then do B.method = A.method; B.method(); then the context is now B and that is what this will point to. The difference becomes very apparent in "handler" type situations where the calling context is usually the object with the handler installed.
Your solution using self is sound.
kentaromiura's answer is absolutely right.
That said, mootools provides function.bind() as a way to decide what this will refer inside of your function. this means that if you simply do this :
var destroy = function () {
`bind() [...]
this.reset();
}.bind(this);
it will work as you intended (that is, this will be the same inside of destroy() and outside).
Now, a lot of coders will balk at fiddling with the context, with good reason as it is very difficult to read and maintain. But here you have it and I think bind() is a very nifty trick of mootools.

Invalid method when method is valid

I have just started a new version of my Crysis Wars Server Side Modification called InfinityX. For better management, I have put the functions inside tables as it looks neater and I can group functions together (like Core.PlayerHandle:GetIp(player)), but I have ran into a problem.
The problem is that the specified method to get the players' name, player:GetName() is being seen as an invalid method, when the method actually is completely valid.
I would like to know if using the below structure is causing a problem and if so, how to fix it. This is the first time I've used this structure for functions, but it is already proving easier than the old method I was using.
The Code:
Event =
{
PlayerConnect = function(player)
Msg.All:CenteredConsole("$4Event$8 (Connect)$9: $3"..player:GetName().." on channel "..player.actor:GetChannel());
System.LogAlways(Default.Tag.."Incoming Connect on Channel "..player.actor:GetChannel());
Event:Log("Connect", player);
end;
};
The below code works when I bypass the function and put the code directly where it's needed:
Msg.All:CenteredConsole("$4Event$8 (Connect)$9: $3"..player:GetName().." on channel "..player.actor:GetChannel());
System.LogAlways(Default.Tag.."Incoming Connect on Channel "..player.actor:GetChannel());
The Error:
[Warning] [Lua Error] infinityx/main/core.events.lua:23: attempt to call method 'GetName' (a nil value)
PlayerConnect, (infinityx/main/core.events.lua: 23)
ConnectScript, (infinityx/main/core.main.lua: 52)
OnClientEnteredGame, (scripts/gamerules/instantaction.lua: 511)
(null) (scripts/gamerules/teaminstantaction.lua: 520)
Any clarification would be appreciated.
Thanks :)
Well, as PlayerConnect is inside the table Event, and you are calling with a ":", add self as first arg in the function, like:
PlayerConnect = function(self, player)
Clearly, player in the first block of code is not the same as player in the second block of code. The problem must be that the caller of Event.PlayerConnect is not passing the same value.
To test that your Event.PlayerConnect function works, try this in the same place as your second block of code:
Event.PlayerConnect(player)
That should work as you expect.
So, the problem comes down to how Event.PlayerConnect is called without the second block of code. I'm not familiar with that game engine so I don't know how it is done. Perhaps reviewing the documentation and/or debugging that area would help. If you print(player) or call the equivalent log function in both cases, you should see they are different. If you can't run in a debugger, you can still get a stack trace with print(debug.traceback("Accessing player, who's value is: "..player)). If there is indeed some kind of table-based player object in both cases, you can try comparing their fields to see how they are different. You might need to write a simple dumping function to help with that.

JUnit Easymock Unexpected method call

I'm trying to setup a test in JUnit w/ EasyMock and I'm running into a small issue that I can't seem to wrap my head around. I was hoping someone here could help.
Here is a simplified version of the method I'm trying to test:
public void myMethod() {
//(...)
Obj myObj = this.service.getObj(param);
if (myObj.getExtId() != null) {
OtherObj otherObj = new OtherObj();
otherObj.setId(myObj.getExtId());
this.dao.insert(otherObj);
}
//(...)
}
Ok so using EasyMock I've mocked the service.getObj(myObj) call and that works fine.
My problem comes when JUnit hits the dao.insert(otherObj) call. EasyMock throws a *Unexpected Method Call* on it.
I wouldn't mind mocking that dao in my test and using expectLastCall().once(); on it, but that assumes that I have a handle on the "otherObj" that's passed as a parameter at insert time...
Which of course I don't since it's conditionally created within the context of the method being tested.
Anyone has ever had to deal with that and somehow solved it?
Thanks.
You could also use EasyMock.isA(OtherObj.class) for a little more type safety.
If you can't get a reference to the object itself in your test code, you could use EasyMock.anyObject() as the expected argument to yourinsert method. As the name suggests, it will expect the method to be called with.. well, any object :)
It's maybe a little less rigorous than matching the exact argument, but if you're happy with it, give it a spin. Remember to include the cast to OtherObjwhen declaring the expected method call.
The anyObject() matcher works great if you just want to get past this call, but if you actually want to validate the constructed object is what you thought it was going to be, you can use a Capture. It would look something like:
Capture<OtherObj> capturedOtherObj = new Capture<OtherObj>();
mockDao.insert(capture(capturedOtherObj));
replay(mockDao);
objUnderTest.myMethod();
assertThat("captured what you expected", capturedOtherObj.getValue().getId(),
equalTo(expectedId));
Also, PowerMock has the ability to expect an object to be constructed, so you could look into that if you wanted.
Note also that if you use EasyMock.createStrictMock();, the order of the method calls is also important and if you break this rule, it would throw an unexpected method call.

Why do I get a "Too many input arguments" error when not passing any?

I am working on some simple object-oriented code in MATLAB. I am trying to call one of my class methods with no input or output arguments in its definition.
Function definition:
function roll_dice
Function call:
obj.roll_dice;
When this is executed, MATLAB says:
??? Error using ==> roll_dice
Too many input arguments.
Error in ==> DiceSet>Diceset.Diceset at 11
obj.roll_dice;
(etc...)
Anyone have any ideas what could be causing it? Are there secret automatic arguments I'm unaware that I'm passing?
When you make the call:
obj.roll_dice;
It is actually equivalent to:
roll_dice(obj);
So obj is the "secret" automatic argument being passed to roll_dice. If you rewrite the method roll_dice to accept a single input argument (even if you don't use it), things should work correctly.
Alternatively, if you know for sure that your method roll_dice is not going to perform any operations on the class object, you can declare it to be a static method as Dan suggests.
For more information on object-oriented programming in MATLAB, here's a link to the online documentation.
I believe you can also get around this by declaring roll_dice to be a static method.