当前位置 : 主页 > 网络编程 > JavaScript >

defineProperty

来源:互联网 收集:自由互联 发布时间:2021-06-30
defineProperty // https://github.com/RubyLouvre/avalon/issues/272Object.defineProperty(element, "value", { set: function(newValue) { var node = this.attributes.value if (!node || newValue !== node.value) { this.setAttribute("value", newValu
defineProperty
// https://github.com/RubyLouvre/avalon/issues/272
Object.defineProperty(element, "value", {
  set: function(newValue) {
    var node = this.attributes.value
    if (!node || newValue !== node.value) {
      this.setAttribute("value", newValue)
      avalon.fire(this, "input")
    }
  },
  get: function() {
    var node = this.attributes.value
    return node ? node.value : ""
  },
  enumerable: true,
  configurable: true
})

// http://stackoverflow.com/questions/19325938/trigger-action-on-programmatic-change-to-an-input-value
// 优化版
const src_id = unionObj.id
const target_id = unionObj.target.id

const _uObj = elements[target_id]
const targetDom = elements['#'+target_id]
const srcDom = elements['#'+src_id]

Object.defineProperty(targetDom, "value", {
  get: function() {
    return this.getAttribute("value");
  },
  set: function(newValue) {
    console.log("set");
    this.setAttribute("value", newValue);

    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("change", false, true);
    targetDom.dispatchEvent(evt);
  },
})

$(srcDom).on('input', function(){
  targetDom.value = srcDom.value;
})

$(targetDom).on('change', function(){
  console.log(this.value);
})




// --完善版
function watchConfig(_value, key){
  let bValue = _value
  const that = this
  return {
    get: function(){
      return bValue
    },
    set: function(val){
      bValue = val
      that.form[this.id] = val
      that.elements['#'+this.id] ? that.elements['#'+this.id].value = val : ''
    },
    enumerable: true,
    configurable: true
  }
}

// 监控/watch数据
// store: target
// allocation: source
function createStore(store, allocation){
  let wstore = store||{}
  watchConfig = this::watchConfig
  O.keys(allocation).forEach( function(item){
    let _value = allocation[item]
    if (typeof _value != 'object' && typeof _value != 'function') {
      O.defineProperty(wstore, item, watchConfig(_value, item))
    }
    else if (!_value) {
      O.defineProperty(wstore, item, watchConfig(_value, item))
    }
    else if (A.isArray(_value)) {
      O.defineProperty(wstore, item, watchConfig(_value, item))
    }
    else {
      wstore[item] = {}
      createStore(wstore[item], _value)
    }
  })
  return wstore
}
网友评论