2012-08-10 22 views
14

por curiosidad y para aumentar mi conocimiento, quería implementar algún tipo de enlace de datos bidireccional entre los elementos dom y las variables javascript.Enlace de datos bidireccional JavaScript llano

Tuve la suerte de encontrar una respuesta excelente a la mitad de mi problema aquí @ stackoverflow que me llevó a esta esencia https://gist.github.com/384583, pero todavía no puedo hacer la cosa al 100%.

He aquí un ejemplo de mi código: http://jsfiddle.net/bpH6Z/

Si intenta ejecutar el violín y hacer clic en "Ver valor" para ver indefinido, mientras que quiero conseguir el valor real de la atributo del objeto

Probablemente estoy haciendo algo mal debido a mi falta de experiencia con javascript, pero ¿tiene alguna idea de por qué no puedo leer correctamente el atributo 'secret' después de las llamadas _bind() y _watch()?

DESCARGO DE RESPONSABILIDAD: como he dicho, estoy haciendo esto porque quiero un mejor conocimiento de javascript, y no voy a escribir mi marco. Entonces, cualquier "USE FRAMEWORK X" es completamente inútil, ya que podría hacer el trabajo con angularjs.

+0

+1 para jS llano;) – metadings

+0

ist $ refiriéndose a jQuery? Por lo tanto, no es sencillo JS eh – daslicht

+0

Posible duplicado de [Cómo implementar DOM Data Binding en JavaScript] (http://stackoverflow.com/questions/16483560/how-to-implement-dom-data-binding-in-javascript) – Beginner

Respuesta

5

Inténtelo http://jsfiddle.net/bpH6Z/4/

He actualizado su captador/definidor redefinido en el reloj Object.prototype .__, también actualmente el controlador tiene que devolver el nuevo valor.

Actualización: Ahora no se requiere que su controlador devuelva el valor recién establecido.

código actual:

//Got this great piece of code from https://gist.github.com/384583 
Object.defineProperty(Object.prototype, "__watch", { 
    enumerable: false, 
    configurable: true, 
    writable: false, 
    value: function(prop, handler) { 
     var val = this[prop], 
      getter = function() { 
       return val; 
      }, 
      setter = function(newval) { 
       val = newval; 
       handler.call(this, prop, newval); 
       return newval; 
      }; 

     if (delete this[prop]) { // can't watch constants 
      Object.defineProperty(this, prop, { 
       get: getter, 
       set: setter, 
       enumerable: true, 
       configurable: true 
      }); 
     } 
    } 
}); 

var Controller = function() { 
    //The property is changed whenever the dom element changes value 
    //TODO add a callback ? 
    this._bind = function (DOMelement, propertyName) { 
     //The next line is commented because priority is given to the model 
     //this[propertyName] = $(DOMelement).val(); 
     var _ctrl = this; 
     $(DOMelement).on("change input propertyChange", function(e) { 
      e.preventDefault(); 
      _ctrl[propertyName] = DOMelement.val(); 
     }); 

    }; 

    //The dom element changes values when the propertyName is setted 
    this._watch = function(DOMelement, propertyName) { 
     //__watch triggers when the property changes 
     this.__watch(propertyName, function(property, value) { 
      $(DOMelement).val(value); 
     }); 
    }; 
}; 

var ctrl = new Controller(); 
ctrl.secret = 'null'; 
ctrl._bind($('#text1'), 'secret'); // I want the model to reflect changes in #text1 
ctrl._watch($('#text2'), 'secret'); // I want the dom element #text2 to reflect changes in the model 
$('#button1').click(function() { 
    $('#output').html('Secret is : ' + ctrl.secret); //This gives problems 
}); 

HTML actual:

<html> 
<head></head> 
<body> 
    value: <input type="text" id="text1" /><br /> 
    copy: <input type="text" id="text2" /><br /> 
    <input type="button" id="button1" value="View value"><br /> 
    <span id="output"></span> 
</body> 
</html> 
+0

+1 para la revisión – fatmatto

+0

¿Funcionaría esto con IE8 como defineProperty solo funciona en objetos DOM? – Integralist

+0

@Integralist lo más probable es que no, pero hay que intentarlo - tener que reiniciar a XP – metadings

3

Al controlador que pase a su función __watch le falta una declaración return.

this._watch = function(DOMelement, propertyName) { 
    //__watch triggers when the property changes 
    this.__watch(propertyName, function(property, value) { 
     $(DOMelement).val(value); 
     return value; 
    }) 

} 

Debido newval se ajusta a lo que está devuelto desde el controlador, que será undefined sin eso.

+0

+1. Spot on, pásamelo ... Me acabo de dar cuenta de que finalmente también –

+0

+1 para eliminar mi dolor de cabeza – fatmatto

0

he mejorado para múltiples observadores.

http://jsfiddle.net/liyuankui/54vE4/

//The dom element changes values when the propertyName is setted 
this._watch = function(DOMelement, propertyName) { 
    //__watch triggers when the property changes 
    if(watchList.indexOf(DOMelement)<0){ 
     watchList.push(DOMelement); 
    } 
    this.__watch(propertyName, function(property, value) { 
     for(var i=0;i<watchList.length;i++){ 
      var watch=watchList[i]; 
      $(watch).val(value); 
      $(watch).html(value); 
     } 
    }); 
}; 
Cuestiones relacionadas