user3541631 user3541631 - 1 year ago 125
Javascript Question

Javascript: Update the value of an Object fields

I have the following code:

var view = function () {

var formset_prefix = '', form_id = '';

var DOMStrings = {
formset_total: 'TOTAL_FORMS',
formset: '*[id$=-TOTAL_FORMS]',
field: '*[id^=id_' + formset_prefix + '-]',
field_idx = '*[id^=id_' + formset_prefix + form_id +'-]'

};

return {
....................
get_form_fields: function (prefix, id) {
formset_prefix = prefix;
form_id = id;
console.log(formset_prefix);
console.log(DOMStrings.field);
return document.querySelectorAll(DOMStrings.field);
}
..... }();


I don't know at the beginning what is the
formset_prefix
and
formset_id
, but I get them later using multiple function calls, so I initialize them at the beginning with empty.

Hoe can I force the update of the
DOMStrings
object attributes
field
and
formset
later when I update the
formset_prefix
and
formset_id values
?

Answer Source

One option is to make DOMStrings a function and compute the object on the fly:

var formset_prefix = '', form_id = '';

var DOMStrings = function() {
    return {
       formset_total: 'TOTAL_FORMS',
       formset: '*[id$=-TOTAL_FORMS]',
       field: '*[id^=id_' + formset_prefix + '-]'
    }
}

return {
....................
get_form_fields: function (prefix, id) {
            formset_prefix = prefix;
            form_id = id;
            return document.querySelectorAll(DOMStrings().field);
        }
..... }();

Better yet, decouple it from the context, and pass necessary parameters as arguments:

var DOMStrings = function(prefix, id) {
    return {
       formset_total: 'TOTAL_FORMS',
       formset: '*[id$=-TOTAL_FORMS]',
       field: '*[id^=id_' + prefix + '-]'
    }
}

return {
....................
get_form_fields: function (prefix, id) {
            var strings = DOMStrings(prefix, id);
            return document.querySelectorAll(strings.field);
        }
..... }();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download