Bind with coffeescript - coffeescript

How can I call native bind method of function-object with coffeescript ? This is the example of what I am trying to achieve:
window.addEventListener("load",function(e){
this._filter(true);
}.bind(this);
)

Just add some parentheses around the function so that you can .bind the right thing:
window.addEventListener('load', ((e) ->
this._filter(true)
).bind(this))
That will use the native bind method instead of the usual var _this = this trickery that CoffeeScript's => uses.

Related

what does ":" mean in this case in coffee script?

I am new to coffee script. When I am looking at this document https://atom.io/docs/api/v0.198.0/CommandRegistry#instance-add
I see a code segment like,
atom.commands.add 'atom-text-editor',
'user:insert-date': (event) ->
editor = #getModel()
editor.insertText(new Date().toLocaleString())
while the function signature looks,
::add(target, commandName, callback)
So in the code segment, what does : on the second line mean? My understanding is the 'user:insert-date' before : is commandName in the signature. The thing after : is "callback". So : is a argument separator like a ,? I don't find this introduced in the coffee script document http://coffeescript.org
That colon is just part of an object literal. The braces around object literals are optional in CoffeeScript when there's no ambiguity. If we add the optional braces, we get something that looks more like JavaScript:
atom.commands.add 'atom-text-editor', {
'user:insert-date': (event) ->
#...
}
So atom.commands.add is being called with two arguments. The first is the string 'atom-text-editor' and the second is an object with one key ('user:insert-date') whose value is an anonymous function that takes a single argument.
Appending mu is too short's answer (the user is absolutely correct that the second parameter commandNamecan be an object without the explicit braces {})
Atom's sourcecode:
https://github.com/atom/atom/blob/v0.198.0/src/command-registry.coffee#L81
add: (target, commandName, callback) ->
if typeof commandName is 'object'
commands = commandName
disposable = new CompositeDisposable
for commandName, callback of commands
disposable.add #add(target, commandName, callback)
return disposable

In Lift, making a JObject with an inline function

It's common in JavaScript, particularly in jQuery, to have a function call with a literal argument and for a field of that argument to be an inline anonymous function. Like this:
$(function () {
$("#mylist").sortable({
placeholder: "ui-state-highlight",
stop: function () { alert('Hello!'); }
});
});
Is it possible to make such a call from Lift? This is as far as I've gotten:
"#jsonScript" #> Script(js.jquery.JqJsCmds.JqOnLoad(
js.jquery.JqJE.Jq("#mylist") ~> js.JE.JsFunc("sortable", JObject(
JField("placeholder", JString("ui-state-highlight")) ::
JField("stop", js.JE.AnonFunc(js.JsCmds.Alert("Hello!"))) ::
Nil
))
))
The compiler complains that AnonFunc is not a JValue, which is absolutely true: it's not. But in JavaScript a function () {} call is a legal value for a literal object field. How can I let Lift know that?
The long-term goal here is for the function body to eventually be a:
SHtml.jsonCall( JE.Call("jsFunction"), liftFunction _ )
Here is an answer I gave a while back to someone who wanted to integrate Lift with jquery autocomplete, which uses a similar callback method: Lift - Autocomplete with Ajax Submission
I needed to use JsObj:
def render =
"#jsonScript *" #> js.jquery.JqJsCmds.JqOnLoad(
js.jquery.JqJE.Jq("#mylist") ~> js.JE.JsFunc("sortable", js.JE.JsObj(
("placeholder", "ui-state-highlight"),
("stop", js.JE.AnonFunc(SHtml.jsonCall( JE.Call("jsFunction"), liftFunction _)))
))
).cmd

When does the "fat arrow" (=>) bind to "this" instance

The fat arrow can be used in different settings but it somehow doesn't
always bind to the instance I want.
The fat arrow binds at 3 occasions
when declaring a method
when declaring a function within a method
when declaring a function in global context
1. When declaring a method
When the Coffeescript compiler encouters the following syntactical pattern
within a class declaration
class A
somemethod: (paramlist) =>
This will yield the following code within the constructor of class A
this.somemethod = __bind(this.somemethod, this);
That is the definition for that instance is overwriting the initial assignment
with a bound version of the function
2. When declaring a function within a method
When you define a function with a fat arrow within a method the Coffeescript compiler
automatically creates a closure and and shadows this of the outer method into the variable
_this. Any reference to # within the inner function will use the variable _this
in the generated javascript code
somemethod: ->
=> #someCall()
And this is the corresponding Javascript
A.prototype.somemethod = function() {
//_this references this
var _this = this;
return function() {
//and _this is now used within the inner function
return _this.someCall();
};
};
A definition of a function without the fat arrow doesn't create that closure for you.
3. When declaring a function in global context
If you define a free floating function (meaning as a method in a class and not within another function/method) just like this
foo = => #bar
Then the corresponding Javascript will look like this
var foo,
_this = this;
foo = function() {
return _this.bar;
};
The interesting thing here again is that this is being assigned to _this which enables the definition of foo to close over _this.
The important part however is that this is always the global context of your execution environment. If you are in the browser it will be the window object. If you are running node.js it will be the module you are just running.
Warning: You shouldn't define any function accessing your global context anyway. This calls for trouble.

Coffeescript: Invoking call on function declaration

Computed properties on ember views have the form
myComputedProperty: function() {
return doSomething();
}.property()
However, when I write this in coffescript as
myComputedProperty: ->
doSomething()
.property()
I get an error like "Parse error on line 5: Unexpected '.'". Am I doing something wrong, or is this a quirk of the interpreter I'm using (Mindscape VS plugin)?
The grammar of the language doesn't support this. You have to add parenthesis around the function:
myComputedProperty: (->
doSomething()
).property()
You can add () around the function, or you can make the syntax more coffeescript friendly:
prop = (fn) -> fn.property()
myComputedProperty: prop ->
doSomething()

Coffeescript translation

If I have this javascript:
function I_did_something(){
this.test.assertExists('#selector', 'exists');
}
casper.then(I_did_something);
The problem is that casper is using call to call the then method meaning that I cannot do something like this:
#I_did_something = ->
#assertExists('#selector', 'exists')
casper.then #I_did_something
Because this does not refer to the global object.
Can anyone suggest how I would translate this into coffeescript without using the window object preferably?
You can use a fat arrow (=>) to bind the function to the current this:
#I_did_something = =>
#assertExists('#selector', 'exists')
That has a similar effect to:
that = #
#I_did_something = ->
that.assertExists('#selector', 'exists')
and I think that's what you're after.