I am following this railscast https://www.youtube.com/watch?v=ltoPZEzmtJA but I don't use coffeescript. I am trying to convert the coffeescript to javascript but I'm running into a problem.
coffeescript
jQuery -> new AvatarCropper() class AvatarCropper constructor: -> $('#cropbox').Jcrop aspectRatio: 1 setSelect: [0, 0, 600, 600] onSelect: @update onChange: @update update: (coords) => $("#crop_x").val coords.x $("#crop_y").val coords.y $("#crop_w").val coords.w $("#crop_h").val coords.h
js.erb file
$(document).ready(function() { $('.crop-image').on('click', function () { $('#cropbox').Jcrop({ aspectRatio: 1, setSelect: [0, 0, 100, 100], onSelect: update, onChange: update }) }); update: (function(_this) { return function(coords) { $('.user').val(coords.x); $('.user').val(coords.y); $('.user').val(coords.w); return $('.user').val(coords.h); }; })(this) });
I didn't understand why he decided to make a class and thought it would be more complicated to convert the whole thing. The trouble I'm having is the update function. I just plugged his coffee script for the update function into a converter and used the output. This is causing an error saying update is not defined. Where am I going wrong?
Also bonus question: what's the point of him making a class here?
Thanks!
2 Answers
Answers 1
Your syntax looks wrong... :
is used to declare labelled statements.
This is a correct way. Declares an hoisted variable and assign a function ref. to it. The function name can appear in expressed functions too, so it can refer itself intially using its name.
Using var
the function variable should hoist, except the assign value.
/* there are various ways to declare a function */ function update(coords) { var $users = $('.user'); $users.val(coords.x); $users.val(coords.y); $users.val(coords.w); return $users.val(coords.h); }
Answers 2
The point of a class:
- make it more easy to run the same task multiple times on different elements with less room for collisions.
- to help mentally organize your code
To convert, use a site like http://js2.coffee/
var AvatarCropper, bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; jQuery(function() { return new AvatarCropper(); }); AvatarCropper = (function() { function AvatarCropper() { this.update = bind(this.update, this); $('#cropbox').Jcrop({ aspectRatio: 1, setSelect: [0, 0, 600, 600], onSelect: this.update, onChange: this.update }); } AvatarCropper.prototype.update = function(coords) { $("#crop_x").val(coords.x); $("#crop_y").val(coords.y); $("#crop_w").val(coords.w); return $("#crop_h").val(coords.h); }; return AvatarCropper; })(); // --- // generated by coffee-script 1.9.2
0 comments:
Post a Comment