FAQ Database Discussion Community


Sort array of objects in javascript with user input

javascript,arrays,angularjs,sorting,coffeescript
I have to sort an array of objects based on the user input for which I call a function on ng-change. The array needs to be sorted with respect to name in the array of objects. Array is [{"id":1,"name":"android","taggings_count":5,"category":null},{"id":2,"name":"ruby","taggings_count":7,"category":null},{"id":3,"name":"java","taggings_count":3,"category":null}] Function signature is $scope.searchTags = (tagText) -> where tagText is the...

Can I use CoffeeScript to write my Electron (Atom Shell) application?

coffeescript,electron
Does anything special have to be done to get Electron to run my main.coffee file? I have a main.js file (that works) that I converted to CoffeeScript (hence main.coffee), but when I run Electron main.coffee I get an error like the following: App threw an error when running [SyntaxError: /Users/foo/develop/electron/main.coffee:13...

How to export a function from a module to another in coffeesricpt?

coffeescript,amd
For code reuse purpose I want to capture some logic in a single function and have it called in other modules Here is the function definition // Module A define (require) -> doSomething(a, b, c) -> "#{a}?#{b}&#{c}" And here is how the funciton doSomething is used // Module B define(require)...

Compile CoffeeScript to particular Javascript file

javascript,coffeescript
I'm new to using CoffeeScript and this is my first time trying it out. I have two questions. Compile to particular file I want to compile a particular coffee file to javascript on the fly. To do this, I've done the following: coffee -w -o controllers/loginCtrl.js -c coffeescripts/loginCtrl.coffee This gives...

How to insert user_id to coffeescript file

javascript,ruby-on-rails,coffeescript
I'm stacked. Have model User and Event and also fullcalendar. $(document).ready -> $("#calendar").fullCalendar( events: '/events.json' ) Here is my coffeescript file but it doesnt work because it needs to be events: '<%[email protected]%>/events.json'. But ruby-code can't be in coffeescript file, so I need to get user_id. How should I do this?...

Rails 3 show/hide div on edit

ruby-on-rails,coffeescript
I have the following in my view... <fieldset class="learner-registration"> <p> <%= event_form.check_box :requires_registration %> <%= event_form.label :requires_registration, 'Require participants to register (optional)' %> <%= event_form.text_field :evaluator_id, :class => "form-control" %> <span class="help-block">Particpants cannot view Event Location until they enter email and name</span> </p> </fieldset> ...and the following coffeescript... jQuery ->...

Coffeescript evaluates only once

ruby-on-rails,checkbox,coffeescript
I want to make a select all checkbox based on this findle. I made a coffeescript like this: $(document).on 'click','.select_all_clans', -> if $(this).is(':checked') $('.clan_checkbox').attr 'checked', true But it works only when the check_box.clan_checkbox was not selected earlier, and it checks them only once. This is my form: <%= form_tag show_schools_path...

get the progress with animate() JQUERY

javascript,jquery,coffeescript,jquery-animate
Here is the spinet: $('#processing .progress-bar').animate({'width':'60%'},4000); Is it possible to display how the milliseconds are being countdown by the function? for instance I want to be able to display: 4000 3000 2000 1000 0000 then the function stops...

How to combine js lines into one?

coffeescript,mootools
Hi I have several js/mootools code in a coffee file that I want to combine together as in $$("#head").setStyle('border-right-color','#e64626'); $$("#head").setStyle('background','#e64626'); $$("#console").setStyle('border-right-color','#e64626'); $$("#console").setStyle('background','#e64626'); Is it possible to combine this into one line?...

Reactjs best strategy to define a variable for render method

javascript,coffeescript,reactjs
Lets suppose I have this chunk of code, which define the component @authComponent depending on some conditions: @AuthPanel = React.createClass componentWillReceiveProps: -> @authComponent = if @props.uiState.auth_panel?.signed_in <SignOutForm uiState={@props.uiState} socket={@props.socket} /> else <SignInForm uiState={@props.uiState} socket={@props.socket} /> render: -> <div className="navbar-collapse"> {@authComponent} </div> The main trouble which I faced is the difficulty...

Is there a way to concatenate JS and CoffeeScript files using Harp server?

javascript,coffeescript,harp
I would like to request /js/app.js from HarpJS server and have it preprocess a folder of coffeescript and javascript. For example, say I have: /js/module/a.js /js/module/b.coffee /js/module/c.coffee /js/app.coffee Is there a way to request /js/app.js such that the response contains the concatenation of /js/module/a.js, of /js/module/b.js. and /js/module/c.js responses?...

Unique triggering of window.requestAnimationFrame

javascript,coffeescript
I'm using the function window.requestAnimationFrame. I don't know why, but instead of continuous triggering, it is firing just once when I click 'Play' The html is <button id='play'>Play</button> <button id='pause'>Pause</button> The code in coffeeScript class Counter i:0 init: () -> $('#play').click @fire.bind(@) $('#pause').click @unfire.bind(@) fire:() -> window.requestAnimationFrame @update.bind(@) unfire:() ->...

Rails 4 jQuery, javascript and coffee scripts not working

javascript,jquery,ruby-on-rails,ruby,coffeescript
I am new to rails and web development, although I have almost two decades of C/C++ in control systems and firmware, and quite a lot of shell and perl scripting. I can't get jquery to work without explicitly including it, even though it is in the application.js manifest, and I...

Can I add an else to a simplified if statement?

if-statement,coffeescript
I'll be honest, I could not think of what to address this problem as. I was looking on Coffeescript.org to see if there was a nicer way to handle multiple OR's in an if statement They showed an example of displaying this: if (pick === 47 || pick === 92...

Coffeescript and ReactJS documentation

coffeescript,reactjs
I'm searching for a tool to generate documentation for coffeescript AND reactJS both together. I found multiple things for JavaScript, ReactJS or CoffeeScript (eg: codo). I'm also using brunch to glue files and to use exported modules in separated files. Codo is very good but seems not really adapted for...

What's this Coffescript use of then?

syntax,coffeescript,semantics
In Trevor Burnham's book on Coffeescript (p81) he has newcard.save().then => ... Which is not part of a conditional or a switch statement. Is then just a joining word for the syntax or does it have a semantic purpose?...

Angular directive: return object from collection

javascript,angularjs,angularjs-directive,coffeescript
I try to implement a custom directive that list all available plans and allow user to choose one. When plan is selected, the parent scope must be updated with selected object (it is linked with two way binding) It should behave exactly the same as angular ng-options does, but I...

How to disable TableTools buttons in DataTables?

jquery,coffeescript,datatables,jquery-datatables
I am using the latest version of DataTables plugin in my Ruby on Rails app and I want to disable the TableTools buttons(Copy, CSV, Excel, ...) that show up by default, I have tried the following code but it removed the whole table tools panel. $('#myTable').dataTable 'dom': 'T<"clear">lfrtip' oTableTools :...

Extend Coffeescript subclass function from parent in marionette

javascript,backbone.js,coffeescript,marionette
I've got a "FormView" class in my Marionette application that sets up a lot of things for form submissions around my app. I use it every time there is a form. I've also got some helpers that I want to pass into every form template via the templateHelpers method, but...

getWindowHandle() Selenium Webdriver Javascript

javascript,selenium,coffeescript
Made some changes based on help from engineering. Here is the final code I used for grabbing the new window handle: localdriver = @driver @driver.getAllWindowHandles() .then (handles) -> localdriver.switchTo().window(handles[1]) I'm currently running an automation stack that uses Selenium Webdriver, Mocha, Chai, and Grunt. I'm creating scripts in Coffeescript, but an...

Object literal multiple assignment in CoffeeScript

javascript,json,node.js,coffeescript
I'm a bit of a newbie in Javascript. I was looking through a bit of Coffeescript code for an Atom package, and I stumbled upon this piece of code: loadProperties: -> @properties = {} fs.readFile path.resolve(__dirname, '..', 'completions.json'), (error, content) => {@pseudoSelectors, @properties, @tags} = JSON.parse(content) unless error? return I...

Coffeescript incorrect scope of @ when passing method as callback

javascript,coffeescript
When I pass an anonymous function with fat arrows as a socket.io callback and then call another method in the same object (as follows) the scope of @ is correct: module.exports = class InviteCreateSocket extends AbstractSocket register: () -> @socket.on 'invite:create', (data, callback) => @create data, callback create: (data =...

Service property not updating consistently

javascript,jquery,ember.js,coffeescript
So this one may be a little involved. The full app, if you get really stumped and want to run it for yourself, is on github. (If you do, you'll need to login, username and password is in API/tasks/populate.rake... just don't tell anyone else, k?) I'm using Ember State Services...

How to access a variable across CoffeeScript functions?

javascript,coffeescript,global-variables
I use CS in Rails. If I have: foo = -> ... bar = -> ... -> someCount = 123 foo() bar() How can I access someCount inside foo() and bar() without passing it directly as an argument? I thought that this would require declaring someCount as a global variable....

how to use js.coffee file in rails 4

jquery,ruby-on-rails,ruby-on-rails-4,coffeescript
In assets/javascripts/products.js.coffee: jQuery -> $('#product_category_name').autocomplete source: ['foo','food','four'] In products/_form view page: <%= form_for(@product) do |f| %> <div class="field"> <%= f.label :category_name %><br> <%= f.text_field :category_name %> </div> <div class="actions"> <%= f.submit %> </div> <% end %> In layouts/application.js.erb: <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %> <%=...

How do I set a jQuery selector in coffeescript using a variable?

javascript,jquery,ruby-on-rails,coffeescript
Im writing a Rails app, and I have multiple forms on the same page that all have different ids. in coffee script, I'm trying to set the identifier to access the text area in each. heres a quick example of what the html looks like in the browser. HTML <a...

using underscore to total array elements with coffee script

javascript,coffeescript,underscore.js
i have this list which contains an arrays: invoicedItems = [ { sku: 'EP01-MGY1' quantity: 10 unit_price: 473 vat: 0 price: 4730 }, { sku: 'EP01-MGY2' quantity: 80 unit_price: 426 vat: 0 price: 34080 }, { sku: 'EP01-MGY3' quantity: 1 unit_price: 612 vat: 0 price: 612 }, ] what is...

Using after to clean up in mocha, problems with mongo

node.js,mongodb,coffeescript,mocha
Ok, in the after function console.log "enter after function" and console.log "exit" executes, but console.log "WHYYYY" does not execute. I can't figure out why. For the record, console.log 'insert' does execute. I am making a similar call to mongo in one of my tests, so calling mongo should work. Any...

Bluebird nested promises with each/spread

javascript,coffeescript,mongoose,promise,bluebird
I'm facing an issue while using bluebird Promises. I'm using CoffeeScript but JavaScript answers are welcome too :) Here is what I'm trying to do : Code example Promise = require 'bluebird' Model = Promise.promisifyAll(require '[...]') # mongoose model promisified getOpts = () -> [...] # whatever Promise.each [1..3], (number)...

JQuery attr() on div not returning value

jquery,coffeescript,attr
I'm working with a Backbone app written in Coffeescript. I'm trying to access the cid associated with each div in a list of divs. Each div has the same 'contact' class and cid with an associated integer value. <div class="contact-list"> <div class="contact" cid="1"></div> <div class="contact" cid="2"></div> <div class="contact" cid="3"></div> <div...

Dynamic className in cjsx

coffeescript,reactjs
I am trying to hide a component and update the image in a button when I click said button. I have managed to hide the component by doing the follow: {<MyAwesomeComponent /> unless @state.hide} And I change the state by doing: toggleComponent = -> @setState hide: [email protected] . . ....

How to test if class instance is instance of class that it extends?

coffeescript
class A class B extends A b = new B b instanceof B # true b instanceof A # false How I can check that b is "also" instance of A (because B extends A)...

How do I automatically compile Coffeescript using Typesafe?

scala,playframework,coffeescript,typesafe-activator
First of all I would like to mention that I have downloaded "play-scala-intro" template from Playframework official website, after running this project using terminal command ./activator ui (Ubuntu), the Typesafe UI web application started to listen on port 8888, and "play-scala-intro" application on port 9000. At every change and save...

Socket.io server in the browser

javascript,coffeescript,socket.io
I want to use socket.io server in the browser. Why do I need this? I have a difficult real-time app which connected through websockets, but I want to manually test it through web page (send & receive the signals). How can I do that? P.S. Packages like mockSocket aren't feet...

Rails submit_tag form validation

ruby-on-rails,coffeescript
In my view I have: event.html.erb <div class="form-group registration_form"> <%= form_tag(register_learner_path, {remote: true}) do -%> <p> <%= label_tag :email %> <%= text_field_tag :email %> <p/> <p> <%= label_tag "First Name" %> <%= text_field_tag :first_name %> <p/> <p> <%= label_tag "Last Name" %> <%= text_field_tag :last_name %> <p/> <%= hidden_field_tag 'event_id',...

python-like interpolation of string in coffeescript

python,string,coffeescript,string-interpolation
I have such namespace with errors errorMessages= error404Find: "Hosts not found" error404FindByHost: "Host - #{hostName} - not found" error400: "No host" hostName should be assigned to null and overrided in function like: this.hostName = 'smth' or can I use something like in python: errorMessages= {'error404Find': "Hosts not found" 'error404FindByHost': "Host...

Handlebars: return hash from helper

javascript,backbone.js,coffeescript,handlebars.js,handlebars
Can i return hash from Handlebars helper? I tried this: In my view: initialize: -> super this.hash = {key1: 'test1', key2: 'test2'} Handlebars.registerHelper 'show', => return this.hash In template: {{show.key1}} What am i doing wrong? Thanks!...

Coffescript and multiple arguments

coffeescript
I can't see where is the syntax problem here : x = ()->new TranformService() angular.module('rcMovable').factory ( "transformService", x) When there is no problem there x = ()->new TranformService() angular.module('rcMovable').factory "transformService", x Forget about Angular stuff for the moment, I have :2:58: error: unexpected ',' ...

Write Ajax function in Coffeescript?

javascript,jquery,ajax,coffeescript
Fiddle - http://codepen.io/mikethedj4/pen/BNRdVp Today I decided to learn Coffeescript and play around making some functions, handling events, etc: However today I got an error that says, "reserved word 'function'", and haven't figured out how to solve it. Any help is greatly appreciated... Original: $(function () { function download_to_textbox(url, el) {...

what does “:” mean in this case in coffee script?

coffeescript
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...

Coffeescript - assign if value is defined

javascript,coffeescript
What is the best way in Coffeescript / Javascript to assign a value to a object field only if that value is defined? At the moment, I have the following code to assign values to the fields of the ogData object. I want a field to remain uninitalised if the...

Why does Codepen.io not show a thumbnail / preview for this pen?

javascript,jquery,coffeescript
http://codepen.io/fauxnoir/pen/mJwBxm AUDIO_FILE = 'http://matthiasdv.org/cdn/tracks/robbery_song' CODECS = [ 'mp3' ] stats = new Stats() stats.domElement.style.position = 'absolute' stats.domElement.style.left = '0px' stats.domElement.style.top = '0px' # CONFIG FORCE_INWARDS = 1000 RADIUS_INWARDS = 3000 FORCE_OUTWARDS = -200000 RADIUS_OUTWARDS = 400 NUM_PARTICLES = 800 PARTICLE_RADIUS_MULTIPLIER = 0.6 PARTICLE_MIN_MASS = 3.0 PARTICLE_MAX_MASS = 6.0 class Simulation...

Add Extra Field_for in Nested form with Rails 4

javascript,ruby-on-rails,ruby-on-rails-4,coffeescript,nested-forms
I made form where I can make new Entity with all its data, and add new Users that are associated with that Entity using Has_many :through association. Here is the problem. I want to be able to add extra User field li element with button "Add extra user". I can't...

Waiting for Nested Promises to complete

ember.js,coffeescript,promise
I have a complicated object graph I'm building up in an Ember Controller. export default Container({ username: DS.attr('string'), items: DS.hasMany('item') }) export default SomeDetail({ foo: DS.attr('string') }) export default Item({ detail_type: DS.attr('string'), detail_id: DS.attr('number'), container: DS.belongsTo('container') }) So, to set all this up, I'm basically trying to Create the conatainer,...

jstree in complex environment & coffee not showing any icons nor outline

jquery,coffeescript,jstree
I included (jquery) jsTree in my already complex environmemt, and using coffee script, I got a fast 'it works' but now i stuck with no images showing nor getting any outline of the tree displayed Although I think my prob is behind CSS I tell: I want to populate jstree...

ECMA 6 postfix condition use-cases

javascript,coffeescript,ecmascript-6
I was reading the following presentation, and somewhere towards the end it mentions Postfix Conditions to be introduced in ECMA6 script. It provides he following use-case scenario: console.log("42") if question is true; I searched Google for more use-case scenarios and potential advantages to regular conditions. What was the reason for...

Rails 4 - Layouts only showing half the time with javascript

javascript,ruby-on-rails,coffeescript
I made a little script in javascript to display a different image based on the day, it works fine but half the time when I load the page only the image will be displayed and not the rest of the app(no menus) and the other half everything is working perfectly....

How to initialize ng-model of input checkboxes in an ng-repeat loop

javascript,angularjs,checkbox,coffeescript
I've run into an issue when creating multiple input[checkbox]es for a list of items in angular with ng-repeat and attaching an ng-model: <li ng-repeat="item in items"> <a ng-href="#/{{item.id}}" > {{ item.id }} </a> <input type="checkbox" ng-model="selectedMessages[item.id]"/> </li> The issue here is that selectedMessages[item.id] is only initialized and set when the...

Get variable of a class out of the scope with coffeescript

javascript,coffeescript
I have that code : class @Validator ## # Constructor # # Set basic variables # ## constructor: -> @_errors = {} ## # Errors ## errors: first: -> last: -> all: => return @_errors get: -> In the method all() of the object errors it's impossible to reach the...

Coffeescript Inheritance: Static variables/methods

inheritance,express,coffeescript
In other OOP languages, the following is a common form of abstraction class AbstractClass myVar: null @doSomething: -> console.log myVar class Child extends AbstractClass myVar: 'I am a child' Calling Child.doSomething() should print "I am a child". I should also be able to pass Child.doSomething as a callback and have...

D3.js ( in Coffeescript) show data on click

javascript,d3.js,coffeescript,data-visualization
I am in the process of creating a bubble chart with D3.js. Now I want it to display a comment in the <h3 id="comment"></h3> tag when I click on each bubble. Here is my data.csv file: name,count,group,comment apple,5,red,"This is the best apple ever." grape,10,purple,"Grapes are huge." banana,8,yellow,"Are these bananas even...

How to map Visual Studio shortcut keys in Github Atom

visual-studio,coffeescript,atom-editor
How to map the shortcut keys in GitHub Atom just like Visual Studio. If anyone have keymap file kindly share. I tried to implement (Ctrl+K ,Ctrl+C) in github atom for comment. It didnt work. Also Ctrl-K,Ctrl-U to turn off comment 'atom-text-editor': 'ctrl-k+ctrl-c': 'editor:toggle-line-comments' ...

Angular: JSON filter in textarea produces a lot of slashes

javascript,json,angularjs,coffeescript
I have a problem, I have an object which needs to be editable via a textarea. The object is binded via ng-model with the textarea. Because it is JSON it is handy to have it parsed down to a nice style, so I used the json filter build in to...

How to call python from coffeescript

angularjs,python-2.7,coffeescript
I am hacking an example angularjs app created using coffeescript. I'm new to both but have a fair amount of xp with python. How can I call flask from within a coffeescript script? Specifically, the eg app instantiates an array: .controller('tableCtrl', [ '$scope', '$filter' ($scope, $filter) -> # filter $scope.stores...

In lodash.js, will it cache the result for `.value()` method?

javascript,coffeescript,underscore.js,lazy-evaluation,lodash
For example, I have codes (coffeescript) like this: sortedLatLng = _(w) .sortBy (x) -> x.time .map (x) -> [x.longitude,x.latitude] .uniq((x)-> x[0].toFixed(3) + "," + x[1].toFixed(3)) # keep three decimal to merge nearby points console.log(sortedLatLng.value()) myFunction1(sortedLatLng.value()) myFunction2(sortedLatLng.value()) console.log(sortedLatLng.reverse().value()) This may be chained by other lodash method later. Meanwhile, its value may...

setInterval() keeps Node.js process running

javascript,node.js,coffeescript
I'm writing something like a token bucket in CoffeeScript. class TokenBucket constructor: (@speed, @threshold) -> @currentVolume = 0 @interval = setInterval => @currentVolume += 1 if @threshold < @currentVolume @currentVolume = @threshold , @speed * 1000 stop: -> clearInterval @interval return get: -> if @currentVolume == 0 false else @currentVolume...

CoffeeScript: calculate parse tree (like coffee -n) in a program

coffeescript,parse-tree
Is there a way to compute the CoffeeScript parse tree of a program (provided as a string) inside CoffeeScript without calling an external program? For example, let's say I have a string 'square=(n)->n*n' inside a CoffeeScript program. I want to get the same output as storing this string in a...

Gulp compiling SLIM/SASS/CoffeeScript on fly

coffeescript,sass,gulp,slim-lang
There is the following Gulp file with tasks: // gulp var gulp = require('gulp'); // plugins var connect = require('gulp-connect'); var jshint = require('gulp-jshint'); var uglify = require('gulp-uglify'); var minifyCSS = require('gulp-minify-css'); var clean = require('gulp-clean'); var slim = require('gulp-slim'); var coffee = require('gulp-coffee'); var sass = require('gulp-sass'); // tasks...

Rails updating morris.js data dynamically with coffeescript

ruby-on-rails,ajax,json,coffeescript,morris.js
in my Rails app I have a morris.js line chart that works perfectly fine on initial page load. What I'm now trying to accomplish is dynamically updating this chart when certain best_in_place fields in a table are updated (via ajax:success). Updating a morris.js chart requires passing in a new array...

Rails Best_in_place ajax:success not being recognized

ruby-on-rails,ajax,coffeescript,best-in-place
My Rails app contains an Excel-like editable table, using best_in_place fields throughout. They work perfectly fine upon page load and I have no problem calling coffeescript functions on ajax:success after a user edits a best_in_place field. Since this is an Excel-like table, users can click a link to add a...

Coffescript doesnt point correct element

javascript,jquery,coffeescript
Hi I have a coffeescript code like this: $(document).on 'keyup', '.content_length', -> $(this).nextAll('div.char_counter:first').text(255 - $(this).val().length); Which supposed to make this code, works: <div class="create_comment" > <%= form_for(announcement.comments.create, url: announcement_comments_path(announcement.id) ) do |form| %> <%= form.label :author, "Autor:" %> <%= form.text_field :author, class: "form-control" %> <%= form.label :content, "Treść:" %> <%=...

How to require other CoffeeScripts files in main CoffeeScript with Laravel?

php,laravel,coffeescript,asset-pipeline,laravel-elixir
I have one CoffeeScript project with "Ruby on Rails" framework. Now I want to use "Laravel" framework instead of "Ruby on Rails". In "Ruby on Rails", there is "Sprocket" asset pipeline management library. With "Sprocket", I can import other coffeescript files in main coffeescript file with #= require or #=...

Access class instance from a function passed into a React component and triggered there

javascript,backbone.js,coffeescript,reactjs
I have a Backbone/React app. I'm trying to keep all my backbone logic in the backbone View (FoodList in this example), so that I can pass methods into the components, have the components trigger them, and then run the necessary logic within the view (i.e. manipulate backbone collection), keeping backbone's...

Share two instances between other classes

javascript,coffeescript
I have 4 coffeescript classes as the following: class Main constructor: (element) -> @element = $(element) @one = new One() @two = new Two(@one) @dummy = new Dummy(@one, @two) class One constructor: (class_two_instance) -> # do something class Two constructor: (class_one_instance) -> # do something class Dummy constructor: (class_one_instance, class_two_instance)...

Test for Apple Push Notification

node.js,coffeescript,mongoose,apple-push-notifications
I am using node.js (server framework) and mongoose.js (mongo based schema modeling) as the backend for an iOS app and I am using Mocha (test framwork) to make sure everything works. What I really want to know, and can find no documentation on, is how to test on the server...

play a single beep (beep.js)

javascript,coffeescript
i'm trying to create a "generative score" using beep.js based on some map data i have. i am using new Beep.Voice as placeholder for notes associated to specific types of data (7 voices total). as data is displayed, a voice should be played. i'm doing things pretty "brute force" so...

AngularJS - Losing controller scope within method

javascript,angularjs,coffeescript
Angular noob here. I'm trying to create a form as a directive. ng-submit calls a controller action, but, within that method, I don't have access to the controllers scope, ie. $scope. Here's the part that's really confusing me. On my laptop and my desktop, the first time I dropped into...

Reactjs working with sockets: rerender when socket receive a message

javascript,websocket,coffeescript,reactjs
I'm try to implement something like chat application with usage of websockets. But when websocket got a message, no components are rerendering. Please review my code # The main ancestor, chat application @Chat = React.createClass componentWillMount: -> @setState signals: [] # the list of signals received by websockets socket =...

Item not being pulled from array after navigating away from and back to page in Meteor app

mongodb,meteor,coffeescript
So in my Meteor app a user can add themselves to a race or remove themselves too. See below code from my Meteor.methods: update_users_array: ( id, user ) -> if RaceList.find( _id: id, users: $elemMatch: _id: user._id ).fetch().length > 0 RaceList.update id, $pull: users: user else RaceList.update id, $push: users:...

AngularJS - Form scope binding in ng-include templates

angularjs,forms,coffeescript,jade,angularjs-ng-include
I'm fairly new to Angular and I have been porting a webform from Zurb's foundation and nasty JQuery to Angular. I'm attempting to load each section of my webform as a template, while still binding the fields to the scope. The sections of the form are dynamically included from a...

Clearing Session data

javascript,ruby-on-rails,ruby-on-rails-4,coffeescript
In my view I have a button using simple_form gem: <%= simple_form_for(:place_order, :url => "#{}", html: {id: "place_order" }) do |f| %> <%= f.button :button, "Clear Cart", class: "btn btn-primary clearcart", id: "clear_cart", name: "clear_cart" %> <%= f.button :submit, "Continue Shopping", class: "btn btn-success contShop", id: "continue_shopping", name: "continue_shopping" %>...

One of two animations doesn't work on page load jQuery

jquery,css,coffeescript
I'm trying to get both lines of text on the page to animate in on page load. However, the top line works just fine but the bottom one won't show up at all. Can anyone help me out? HTML: <div id="welcome_intro"> <h3 id="welcome">Welcome</h3> <h1 id="apples">apples</h1> </div> CSS: h3, h1 {...

Framer.js: how to get tap coordinates

coffeescript,framerjs
I'm writing a Framer.js function to simulate the 'splash' effect when you tap a button or a layer, as per Google Material Design. It looks something like this tapSplash = (tapX,tapY) -> tapSplashLayer = new layer backgroundColor: "#ffffff" opacity: 0.2 width: 500, height: 1500 borderRadius: 1500 midX: tapX midY: tapY...

React.js implement UI effects after mounting

javascript,dom,coffeescript,reactjs,react-jsx
Let's suppose I have a React class, which has a components - fields with autosize.js and bootstrap form helpers phone libraries. There is a trouble. Because of these few (and a lot of another) libs rendered exactly after DOM is loaded, I need to manually implement these libraries to components...

Theoretical Coffeescript Switch Statement Conundrum

javascript,coffeescript,switch-statement,theory
preface This probably has no real implementation but after reading another post on coffeescript's 2 switch usages, I decided to play around with it and found this rather odd issue. coffeescript type = 'guidance' s = switch when type is 'guidance' 'g' when type is 'vulnerability' 'v' else 'foo' console.log...

async.mapLimit usage to make multiple requests

javascript,node.js,asynchronous,coffeescript
i have such line: async.mapLimit(urls, 10, getCertificatesFromPage, callback) where urls is an array with urls, getCertificatesFromPage : getCertificatesFromPage = (url, callback) -> request url, (err, res, html) -> $ = cheerio.load(html) allRows = $('div.search-result-shop') objCollector = [] allRows.each () -> links = $(this).find('a') obj = companyName: $(this).find('.companyname').text() pageDetailsUrl: '' link:...

Coffeescript and Ecmascript 6 get and set keywords

coffeescript,ecmascript-6
I'm running into an issue with coffeescript where I would like to be able to use the ecmascript get and set keywords, however the syntax doesn't make sense in coffeescript. Here's an example of the original javascript // A Tutorial class that takes a document in its constructor Tutorial =...

Dynamically generate React component names

coffeescript,reactjs
I'm having trouble finding a solution to this. How can I convert the code below into something more dynamic and succinct? OneComponent = require ('./OneComponent') TwoComponent = require ('./TwoComponent') ThreeComponent = require ('./ThreeComponent') Example = React.createClass render: -> filter = @props.filterState if filter is 'something' tableCmpt = <div> <OneComponent tasks={@props.tasks}...

PyCharm coffee filewatcher

django,coffeescript,pycharm
I got this directory structure (django project): -myproject +mysite -myapp -static -myapp -script -coffee +views +controllers +models app.coffee -js +views +controllers +models manage.py How can i set coffeescript watcher to save *.js files in the same subdirectory of js directory. For example: /coffee/app.coffee -> /js/app.js /coffee/views/myview.coffee -> /js/views/myview.js...

Coffeescript implicit returns impact on performance and side effects

javascript,node.js,express,coffeescript
I am currently working on a node.js web service which utilizes Express.js and Mongoose. Recently, I figured I would try my hand at CoffeeScript, as I have heard that there are some benefits to be had. However, I have noticed something a little unsettling, and I was curious if someone...

Set Session with usernames value

meteor,coffeescript
I try to query the current username which is logged in and set the value to a Session. Finally, it seems to be working but in browsers console I get the following Exception: Exception in template helper: TypeError: Cannot read property 'username' of undefined Template.dashboard.helpers 'setUsernameToSession': -> user = Meteor.users.findOne(Meteor.userId())...

ActionController::RoutingError Rails and Angular

javascript,ruby-on-rails,angularjs,coffeescript,restangular
Every time ProductController is called and Restangular getting data from the rails server. I got this error ActionController::RoutingError (No route matches [GET] "/products.json/6862"): I thought if product.json/:id is the route with rails it will automatically go to show view (show.json.jbuilder). Any idea what did I miss? ProductController.js.coffee controllers = angular.module('controllers')...

Backbone.Deferred.Model: Why the unittest is not run?

backbone.js,coffeescript,phantomjs,mocha,chai
Here is the code in question. define (require) -> Backbone = require 'backbone' require 'backbone-deferred' class Data extends Backbone.Deferred.Model urlRoot: 'data' parse: (resp) -> resp.record or resp isValid: -> @get 'valid' # Newly introduced dataUrl: -> @get('data_url')?.replace /abc/, '' And here is the unit test define (require) -> Data =...

Rails: redirect_to:back not redirecting in spite of showing correct logs

javascript,ruby-on-rails,ruby,angularjs,coffeescript
My html <div class="modal-body center"> <form method="post"> <textarea ng-model = "post.review" rows="10" cols="50" name="review" placeholder="something thougtful and helpful" style = "color: red;" class="fsField fsRequired fsTextAreaMaxLength", maxlength = "116"></textarea> <input ng-model = "post.rating" type="integer" name="rating" placeholder="0-10" style="color: red;" class="fsField fsRequired fsTextAreaMaxLength", maxlength = "116"> <button ng-click = "submitReview(product)" class="btn btn-success"...

Websocket establish bulletproof connection

javascript,firefox,websocket,coffeescript
My coffee code to establish websocket connection when it isn't present return an error: socket = new WebSocket('ws://localhost:8080') #=> Firefox can't establish a connection to the server at ws://localhost:8080/. #=> socket = new WebSocket('ws://localhost:8080'); It's normal behaviour of WebSocket, but I want WebSockets work like this: # pseudocode if websocket.establish_connection()...

unable to handle HTTP 422 with best in place rails

jquery,ruby-on-rails,coffeescript,best-in-place
I have my controller code like this: def update respond_to do |format| if refresh_quantity_in_inventory format.json { render json: { message: "Quantity successfully updated" } } else format.json { render json: @errors, status: :unprocessable_entity } end end end The CoffeeScript for this is like this: ready = -> $('#best_in_place_cart_quantity').best_in_place().bind 'ajax:error', (evt,...

Chrome extension popup has a 2 - 3 second delay

javascript,performance,google-chrome-extension,coffeescript
I have a todo list Chrome extension where all of the code is in the content. There's nothing in background.js – mainly because I also deploy this app as a standalone website. There's a 2 - 3 second delay between clicking on the extension's browser action and the popup rendering....

require (browserify) not working correctly when assigned (empty object), but works when inline

javascript,coffeescript,reactjs,browserify
I have the following component definitions in React (coffee jsx): CompUtils = require './../utils/comp-utils' ... render: -> console.log CompUtils # prints {} (empty object) <div> Then {CompUtils.getConstructComponent @props.construct, @props.onUpdate, @props.onRemove} </div> But this works: render: -> console.log require('./../utils/comp-utils') <div> Then {require('./../utils/comp-utils').getConstructComponent @props.construct, @props.onUpdate, @props.onRemove} </div> I am absolutely confounded by...

path to assets in Wordpress using jQuery

jquery,wordpress,coffeescript
Hi i'm trying to replace the add to cart button by a loading image in jquery but I can't seem to find the write path using jquery. This is my code in coffee: $('.add_to_cart_button').click -> templateDir = "<?php bloginfo('template_directory') ?>" ajaxImage = document.createElement("img") ajaxImage.setAttribute("src", templateDir + "/static/img/ajax-loader.gif") $(@).replaceWith(ajaxImage) this outputs...

Do not allow decimal numbers in textfield on form submittion in CoffeeScript

jquery,coffeescript
I have a textfield in HTML form. On form submition i want to prompt the user if a decimal number is entered. How can i do it using a regular expression in cofeescript? jQuery('form#adjustment_invoice_form input[type=submit]').live 'click', -> if !(/[^0-9]/.test(adj_value)) alert("Decimal numbers are not allowed for") false ...

How to bind response of Ajax request to Model in EmberJs?

javascript,ruby-on-rails,ember.js,coffeescript,emblem.js
I am new to Ember, I have a running application where I need to put Chat app in it. I need to have list of last messages of different users from Chat model (Rails end) {Done} On clicking any message I will have a list of conversation of that particular...

Ajax polling in Coffeescript - whats falling out of scope and why?

javascript,jquery,coffeescript,polling
I'd like to reload an iframe when the images needed to generate the preview it will display are cached by background workers (which can take a little while.) class Preview constructor: (preview) -> @preview = preview @loadWhenCachedPoll() unless @preview.data?.footprintsCached? loadWhenCachedPoll: -> @interval = null @interval = setInterval(@loadWhenCached(), 3000) loadWhenCached: ->...

Angularjs service typerror undefined is not a function

javascript,angularjs,coffeescript
I have a service in coffeescript like so: App.service 'CalculateService', -> @Calculate = (student) -> if student.type == 'MatureStudent' student.age + 10 else student.age + 5 JS version App.service('CalculateService', function() { return this.Calculate = function(student) { if (student.type === 'MatureStudent') { return student.age + 10; } else { return student.age...

locating path of a file in meteorjs

javascript,node.js,meteor,coffeescript,npm
I have a project in meteorjs that is using the nodes filesystem to read file, but I am not able to locate the file to be read. My file Location Server - startup - app.load.coffee - myfileToBeRead.txt My try in app.load.coffee fs = Npm.require('fs') console.log fs.readFileSync 'server/startup/myfileToBeRead.txt' I am not...

Creating functions containing HTML

javascript,html,string,function,coffeescript
I'm trying to create a Coffescript function that contains common HTML for a frequently re-used object in my page. I'm passing a variable to the function with the text I want changed each time. Every time I try to compile my Coffeescript, I get this error: [stdin]:6:5: error: unexpected identifier...

Jasmine spyOn with multiple returns

javascript,angularjs,coffeescript,jasmine
I would like to test my angular application with Jasmine. So I created some tests, most of them work fine. But, one of my functions require the user to fill in an prompt. Tests can not fill this prompt, so I mocked them with spyOn(window,'prompt').and.returnValue('test'). This works, but only once....

Can't call fetch directly in Backbone model listenTo

javascript,backbone.js,coffeescript
I'm trying to have a model listen to a collection and fetch itself when the collection changes: class Team extends Backbone.Model urlRoot: '/team', initialize: function(attributes, options) { this.listenTo(members, 'change', this.fetch) The fetch does seem to trigger, but the url is all messed up, and to get it to work I...

Post forms with coffescript/ ajax in play

ajax,forms,playframework,coffeescript
I try to submit a simple form with coffeescript/ajax in play. But I'm doing something wrong and can't figure out what. I started with a working form for creating questions (without ajax) and then followed Playframwork doc on javascript routing: So first I created the router resource in my Application...

angularjs calculate expression and assign to model

javascript,angularjs,coffeescript
I have an expression in an ng-repeat that calculate various inputs in a table row and returns gross pay like so: Controller App.controller 'calcPayCtrl', ($scope, $filter, Api, employments) -> active_employments = $filter('filter')(employments, {status: 'active'}) $scope.employments = active_employments angular.forEach $scope.employments, (employment) -> payslip = {employment_id: employment.id} employment.payslip = payslip VIEW <td>...

Show the subcategories of the chosen category in Rails 4

javascript,ruby-on-rails,ruby-on-rails-4,model-view-controller,coffeescript
1. In my **view/gigs/new.html.erb i use <%= f.collection_select :category_id, Category.all, :id, :name, {prompt: "Choose a category"} %> <%= f.collection_select :subcategory_id, Subcategory.all, :id, :name, {prompt: "Choose a subcategory"} %> It creates this and when clicked the below image: From the picture above as you see depending on what category i choose,just...