Javascript:更新Object字段的值

时间:2017-10-03 08:32:30

标签: javascript javascript-objects

我有以下代码:

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);
        }
..... }();

我一开始并不知道formset_prefixformset_id是什么,但我稍后会使用多个函数调用来获取它们,所以我在开头用空格式初始化它们。

当我更新DOMStringsfield时,我可以强制更新formset对象属性formset_prefixformset_id values吗?

2 个答案:

答案 0 :(得分:2)

一个选项是使DOMStrings成为一个函数并动态计算对象:

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);
        }
..... }();

更好的是,将它与上下文分离,并将必要的参数作为参数传递:

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);
        }
..... }();

答案 1 :(得分:1)

有多种方法可以做到这一点。

您为view定义formset_prefix - form_idDOMStringsview的方式为私有。一个选项可以是创建函数来设置formset_prefixform_id的值,这些值也会更新DOMStrings。例如:

var view = function() {

  var formset_prefix = '',
      form_id = '';

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

  return {
    /* .................... */
    get_form_fields: function(prefix, id) {
      console.log('formset_prefix = ' + formset_prefix);
      console.log('DOMStrings.field = ' + DOMStrings.field);
      return document.querySelectorAll(DOMStrings.field);
    },
    /* Setter for formset_prefix */
    set_formset_prefix: function(prefix) {
      formset_prefix = prefix;
      DOMStrings.field = '*[id^=id_' + formset_prefix + '-]';
      return this;
    },
    /* Setter for form_id */
    set_form_id: function(id) {
      form_id = id;
      return this;
    }
    /*.....*/
  }
}();


/* Note: when you return "this" you can chain the method calls
   and now you can do someting like the following
*/

var fields = view.set_formset_prefix('my-prefix')
                 .set_form_id('my-form-id')
                 .get_form_fields('my-prefix', 'my-form-id');