Reputation: 23
I created a currency converter object and it works great except in IE. None of options get appended to the select element. I have been trying to find a solution for hours but can't figure out what is going on. I am new to javascript so I may be doing something completely wrong just not sure what. It seems like the render method is not getting called from within fetch. Thanks
var CurrencyConverter = {
// Initialize Currency Converter
// total: jQuery wrapped object that contains the price to convert
// select: jQuery wrapped select element to render the options tag in
init: function (total, select) {
var that = this;
this.total = total;
this.base_price = accounting.unformat(this.total.text());
this.select = select;
this.fetch();
select.change(function () {
var converted = '',
formated = '';
fx.settings = { from: fx.base, to: this.value };
converted = fx.convert(that.base_price);
formated = accounting.formatMoney(converted, { symbol: this.value, format: "%s %v", precision: "0" });
$(that.total).text(formated);
});
},
// Render Currency Options
render: function () {
var that = this,
accumulator = [],
frag = '';
for (var propertyName in fx.rates) {
accumulator.push(propertyName);
}
$.each(accumulator, function ( i, val ) {
var the_price = $(document.createElement('option')).text(val);
if (val == fx.base) {
the_price.attr('selected', 'true');
}
// TODO: not optimal to run append through each iteration
that.select.append(the_price);
});
},
// Fetch & set conversion rates
fetch: function () {
var that = this;
// Load exchange rates data via the cross-domain/AJAX proxy:
$.getJSON(
'http://openexchangerates.org/latest.json',
function(data) {
fx.rates = data.rates;
fx.base = data.base;
that.render();
}
);
}
};
if ($('#currency-select')) {
CurrencyConverter.init($('#price'), $('#currency-select'));
}
Upvotes: 1
Views: 117
Reputation: 94101
Your problem is scope.
init: function (total, select) {
var that = this; // Ok, `that` is `init`...
this.total = total;
this.base_price = accounting.unformat(this.total.text());
this.select = select; // So `init.select = select`...
.
.
.
render : function () {
var that = this, // Ok, `that` is `render`
accumulator = [],
frag = '';
.
.
.
that.select.append(the_price); // ?????
The easiest way to solve this, is to create a constructor function instead of a literal object so you can pass $select
as an object to which you have access within any method.
var CurrencyConverter = function($select){
this.init = function(){ ... }
this.render = function() { $select.append('...'); }
.
.
.
};
var currency = new CurrencyConverter($('select'));
Upvotes: 1
Reputation: 3740
Ye, i've ran too in this. Don't know if it's the right way to solve this but it works, implying that.select is a jQuery result:
that.select.get(0).add(the_price.get(0))
Upvotes: 1