Created
July 17, 2015 02:38
-
-
Save sdilshod/f7ab502b8d1dac054b18 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TextFieldCalculator | |
config: | |
ui: | |
openLinkSelector: '[role=open-calculator]' | |
sourceTextfieldSelector: '[role=calculator-source-field]' | |
inputfieldSelector: '[role=calculator-input-field]' | |
constructor: ()-> | |
@bindings() | |
@$el = $ '[role=calculator-container]' | |
@result = 0 | |
@currentOperation = null | |
@history = '' | |
bindings: => | |
@bindOpenLink() | |
@bindCalculator() | |
bindOpenLink: => | |
form = @form() | |
inputField = @config.ui.inputfieldSelector | |
$(@config.ui.openLinkSelector).on 'click', (e)-> | |
e.preventDefault() | |
$('body').append form | |
elOffset = $(@).offset() | |
$('[role=calculator-container]').css({top: elOffset.top+20, left: elOffset.left}) | |
$(inputField).focus() | |
false | |
bindCalculator: => | |
$('body').on 'keyup', @config.ui.inputfieldSelector, (e) => | |
@calculate(e) | |
console.log 'key up' | |
$('body').on 'keydown', @config.ui.inputfieldSelector, (e) => | |
console.log 'key down' | |
console.log e.keyCode | |
#if $.inArray(e.keyCode, [13, 43, 45, 42, 47]) >= 0 | |
# console.log 'key down' | |
# console.log e.charCode | |
$('body').on 'keypress', @config.ui.inputfieldSelector, (e) => | |
console.log 'key press' | |
console.log e.charCode | |
#if $.inArray(e.which, [13, 43, 45, 42, 47]) >= 0 | |
# console.log 'key press' | |
calculate: (event)=> | |
if $.inArray(event.which, [13, 43, 45, 42, 47]) >= 0 | |
event.preventDefault() | |
el = $(@config.ui.inputfieldSelector) | |
if @result == 0 | |
@result = el.val() | |
else | |
#console.log "@result = #{@result} #{@currentOperation} #{el.val()}" | |
eval("this.result = #{@result} #{@currentOperation} #{el.val()}") unless el.val() == '' | |
@currentOperation = @getAriphmetic(event.which) unless event.which == 13 | |
@writeHistory(el) | |
el.val('') | |
console.log @result | |
getAriphmetic: (keyCode) => | |
switch keyCode | |
when 43 then "+" | |
when 45 then "-" | |
when 42 then "*" | |
when 47 then "/" | |
writeHistory: (el) => | |
@history = "#{@history} #{el.val()} #{@currentOperation}" | |
$('[role=calculator-input-history]').html @history | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment