I’ve been exploring these days how to create a definition of some method outside of it’s class. Usually there is no need to do that, but I had to write a class which works as a calculator with different input fields. Each input field has it’s own custom formula and I really wanted to avoid the eval() function.
The idea is simple: to create a class with some extra empty function (method), which can be defined from the outside, more specificly through it’s object in it’s custom way.
class Test {
initialize: function(){
...
this.my_extra();
},
function_1: function(){...},
function_2: function(){...},
my_extra: function(){ return 0; }
}
var A1 = new Test();
A1.my_extra = function(a){
return a * a;
}
I tested this functionality in many different ways and I must say it works fine in almost any way you want. Outside methods can use arguments, call other class’s methods, call $(el) objects, and so on… You don’t even have to define an empty method inside the class, but it is convenient because you don’t know if it will be defined by object or not.
The numberConverter class
And here is my calculator with three input fields: tax, price, full price. By changing any of those fields the other two fields must re-calculate. Each field has it’s own calculation formula, it’s own event and affects a different field.
HTML:
<div id="page">
<select id="tax">
<option value="0">0</option>
<option value="20">20</option>
</select>
<input id="price" type="text" />
<input id="full_price" type="text" />
</div>
JS:
var p = new numberConverter('price',{
onEvent: 'keyup',
affects: 'full_price'
});
p.formula = function(){
return p.val() * (1 + p.val('tax') / 100);
}
var t = new numberConverter('tax',{
onEvent: 'change',
affects: 'full_price'
});
t.formula = function(){
return t.val('price') * (1 + t.val() / 100);
}
var f = new numberConverter('full_price',{
onEvent: 'keyup',
affects: 'price'
});
f.formula = function(){
return f.val('full_price') / (1 + f.val('tax') / 100);
}
You can see that every new object defines it’s own calculation formula, which uses the val method from class to adjust decimal points and decimal places.
The numberConverter demo is here.