How to share functions in Coffeescript? Rails - ruby-on-rails

I have one function that should be used in two different events, but I can't make it work. Where am I making a mistake? Or do I have to use Class instead?
coment_error = (that) ->
$this = $(that)
$new_answer = $this.parent('.new_answer')
$new_answer.on('ajax:success',((evt, data, status, xhr)->
$new_answer.hide()
$('.open').show()
))
$new_answer.on('ajax:error',((evt, data, status, xhr)->
$(this).addClass("error")
))
$(document).on("click", ".new_answer > INPUT[type='submit']", coment_error($(this)))
$(document).on("click", ".new_comment > INPUT[type='submit']", coment_error($(this)))

I think the problem is that the last two lines execute the function immediately instead of when the events are called.
$(document).on("click", ".new_answer > INPUT[type='submit']", coment_error)
Also you don't want coment_error to receive "that" because "this" will automatically be bound to the clicked element. So you can get right down to $this = $(this).

Related

How to save boolean conditions and evaluate later

I need to create a structure. The structure must contain an array of "boolean conditions". Something like this:
function ReturnStructure ()
local structure = {
{A < 10},
{B == "smth"},
{FunctionReturnsTrueOrFalse(params)},
--...
}
return structure
end
structure = ReturnStructure()
print(structure[1][1]) -- prints true or false depending on the value of A
In fact these tables contain true or false, not conditions, because when we call function ReturnStructure and it creates a local table structure, all conditions in the fields will be executed. I want to create a structure whose fields will contain not boolean values, but something that I can execute (when I want to do it) and get a boolean value. I can achieve this by using anonymous functions:
function ReturnStructure ()
local structure = {
{function() return A < 10 end},
{function() return B == "smth" end},
{FunctionReturnsTrueOrFalse, params}, -- I don't call function in this line, a just put its adress and parameters to table.
--...
}
return structure
end
structure = ReturnStructure()
print(structure[1][1]) -- prints function: 0x109bdd0
print(structure[1][1]()) -- prints true or false. I execute condition in this string.
So, there is a code which works as I want it to, but it seems very ugly.
I want to hear some ideas on how to create a simpler and more beautiful table, without printing function () return ... in every field. I think that I should use a simple OOP implementation to create my structure as an object, but I don't know how to do it. I also will be happy to get some references to methods, implementations, articles etc., which can help me to find some ideas.
I want to hear some ideas on how to create a simpler and more beautiful table, without printing function () return ... in every field.
There aren't. If Lua had C#'s lambda syntax, you could write:
local structure = {
() => A < 10,
() => B == "smth",
() => FunctionReturnsTrueOrFalse(params),
But Lua likes to keep things small and simple, to avoid adding size and complexity to the language and its implementation, so we have one syntax for one function type.
You could store them as strings, then compile and run them later, but that's choosing form over function. You don't want to be invoking the compiler unnecessarily.
local structure = {
'A < 10',
'B == "smth"',
'FunctionReturnsTrueOrFalse(params)',
So your original solution is better. I don't particularly like the way that the first two items defer evaluating their arguments, while your third example evaluates the parameters at compile time. It would be more consistent to treat the FunctionReturnsTrueOrFalse the same
local structure = {
function() return A < 10 end,
function() return B == "smth" end,
function() return FunctionReturnsTrueOrFalse(param1) end,
This also means you don't need to put them in tables. Each is just a function you call, which simplifies the calling code as well.
If you really wanted to evaluate FunctionReturnsTrueOrFalse's arguments at compile time, I'd write a utility routine to build a closure from a function and its arguments:
local function bind(f, ...)
local args = {...}
return function() f(unpack(args)) end
end
Then use that to bind the function to its args:
local structure = {
function() return A < 10 end,
function() return B == "smth" end,
bind(FunctionReturnsTrueOrFalse, param1, param2, param3),
Then everything in your table is simply a function so you don't need special handling
function ReturnStructure ()
local structure = {
{'A < 10'},
{'B == "smth"'},
{FunctionReturnsTrueOrFalse, 'parameter'},
}
local function call_me(f, ...)
return (type(f)=='function' and f or
assert((load or loadstring)('return '..f)))(...)
end
return setmetatable({}, {
__index =
function(t,k)
if structure[k] then
return call_me((table.unpack or unpack)(structure[k]))
end
end,
__newindex = function(t,k,v) structure[k] = v end
})
end
A = 2
B = "anything"
function FunctionReturnsTrueOrFalse(par)
return #par > 5
end
structure = ReturnStructure()
print(structure[1]) -- true
print(structure[2]) -- false
print(structure[3]) -- true
structure[4] = {'1==0'}
print(structure[4]) -- false

Function with multiple names

In JavaScript you can do this to assign a function to multiple references:
z = function(){
console.log(1)
}
x = y = z
Now when we call x or y, 1 gets printed to the console.
Is this possible in dart?
Yes, just like in JavaScript, functions are first class citizens and can be assigned to variables.
Also see this somewhat older, but still relevant video Functions are Fun, Pt2.
As Example from the video:
loudPrint(String msg) {
print(msg.toUpperCase());
}
var loudify = loudPrint;
loudify('Dart is fun');
// DART IS FUN

on fetch collection is getting zero in backbone

edit method
editCollection: (event) ->
#collection = new BackboneDemo.Collections.Backbonescripts()
#collection.url = "/demos/#{event.target.id}/test"
#collection.fetch()
#collection.on('sync', #selectCheckbox(event), this)
selectCheckbox: (event) ->
console.info #collection.length
#collection.each (test) ->
$('#'+event.target.id+'.test #'+test.get('id')+'.test_checkbox').prop('checked', true);
i even tried to use the reset and on success of the fetch...but length is zero
i know that back bone is lazy loading
How to use wait till fetch is completed......?
Replace those lines on:
editCollection: (event) =>
. . .
selectCheckbox: (event) =>
. . .
This is a function call:
#collection.on('sync', #selectCheckbox(event), this)
# ---------------------^^^^^^^^^^^^^^^^^^^^^^
You're calling #selectCheckbox and passing its return vale to #collection.on as though you said this:
x = #selectCheckbox(event)
#collection.on('sync', x, this)
so you're calling #selectCheckbox before the 'sync' event happens. I think you want to say this:
#collection.on('sync', #selectCheckbox, #)
# ---------------------^^^^^^^^^^^^^^^ Now just a function reference
Also, you should be careful of your indentation inside selectCheckbox or your #collection.each will be iterating with an empty function:
selectCheckbox: (event) ->
console.info #collection.length
#collection.each (test) ->
$("##{event.target.id}.test ##{test.get('id')}.test_checkbox").prop('checked', true)

how to copy link name to title

i wanna ask how to change title in
name
so i want to make link name copy to title automatic
so if i make this code
title link
to
title link
how to do that in php or javascript
i know some in php
but need to make all words in link at database or make for every link variable $
can some one help me in that?
I'd suggest:
function textToTitle(elem, attr) {
if (!elem || !attr) {
// if function's called without an element/node,
// or without a string (an attribute such as 'title',
// 'data-customAttribute', etc...) then returns false and quits
return false;
}
else {
// if elem is a node use that node, otherwise assume it's a
// a string containing the id of an element, search for that element
// and use that
elem = elem.nodeType == 1 ? elem : document.getElementById(elem);
// gets the text of the element (innerText for IE)
var text = elem.textContent || elem.innerText;
// sets the attribute
elem.setAttribute(attr, text);
}
}
var link = document.getElementsByTagName('a');
for (var i = 0, len = link.length; i < len; i++) {
textToTitle(link[i], 'title');
}
JS Fiddle demo.
And since it seems traditional to offer a concise jQuery option:
$('a').attr('title', function() { return $(this).text(); });
JS Fiddle demo.
If you don't want to use a library:
var allLinks = document.getElementsByTagName('a');
for(var i = 0; i < allLinks.length; i++){
allLinks[i].title = allLinks[i].innerHTML;
}
Since you wanted to do all this to one element on the page, consider using something like this:
var allLinks = document.getElementById('myelement').getElementsByTagName('a'); // gets all the link elements out of #myelement
for ( int i = 0; i < allLinks.length; i++ ){
allLinks[i].title = allLinks[i].innerHTML;
}
Actually, this is roughly the same as before but we are changing the input elements.
Or, assuming you use jQuery, you could do something like this:
$('a').each(function(){ // runs through each link element on the page
$(this).attr('title', $(this).html()); // and changes the title to the text within itself ($(this).html())
});
In JQuery you can change an attribute by knowing the current tag and using the .attr() feature. Something like $('a').attr('title', 'new_title'); http://api.jquery.com/attr/

ES5 shim for binding functions is Javascript

Below is a ES5 shim for JS binding.I dont understand self.apply in the bound function.
I know how to use apply method, but where is self pointing to in this case ? It it supposed to be a
function, but here self looks like an object.
if ( !Function.prototype.bind ) {
Function.prototype.bind = function( obj ) {
var slice = [].slice,
args = slice.call(arguments, 1),
self = this,
nop = function () {},
bound = function () {
return self.apply( this instanceof nop ? this : ( obj || {} ), // self in this line is supposed
to // represent a function ?
args.concat( slice.call(arguments) ) );
};
nop.prototype = self.prototype;
bound.prototype = new nop();
return bound;
};
}
self is being used in the shim you have listed to accommodate the fact that this changes along with scope changes. Within the direct scope of the Function.prototype.bind function this will refer to the object on which the bind function was called.
Once you enter the scope of the nested bound function this has changed; so the author has assigned self = this within the bind function to allow the value of this at the time bind is called to remain available to the bound function via lexical scoping (closure).
Scoping within JavaScript can get pretty complicated; for a detailed explanation take a look at this article.
Everything you wanted to know about JavaScript scope.
Have in mind that in javascript almost everything is an object.
So you have it right there:
self = this
So, self is not representing anything, self is the instance.

Resources