0

I have a object with name value. Is it possible to bind that value to html element? - like angularjs

if so what is the correct way? or is it not possible?

here is my demo :

var ob = {};

ob.name = "Testing";

$('div').text(ob.name);

$('button').on('click', function(){

 ob.name = "Update Name";
  
  console.log( ob.name ) //name updates

})
button{
  border:1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <h1></h1> <!-- on click nothing updates automatically -->
</div>
<button>Click Here</button>
user2024080
  • 1
  • 14
  • 56
  • 96
  • `$('div').text(ob.name);` will update the text..You do not have that in click handler.. You are looking for something like `two-way-binding` but it does not happen on its own! – Rayon Mar 29 '16 at 05:41
  • 2
    This might help: http://stackoverflow.com/questions/16483560/how-to-implement-dom-data-binding-in-javascript – Rajesh Mar 29 '16 at 05:44
  • the answer from Rajesh helps me. – user2024080 Mar 29 '16 at 05:54

2 Answers2

1

JavaScript itself doesnt support bidirectionalBinding from scratch.

To make your example work simply add the expression, that you have already figured out correct, to your onClickFunction.

var ob = {};

ob.name = "Testing";
$('div').text(ob.name);


$('button').on('click', function(){

 ob.name = "Update Name";
        $('div').text(ob.name); <!-- add here -->
  
  console.log( ob.name ) //name updates

})
button{
  border:1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <h1></h1> 
</div>
<button>Click Here</button>

Just to clarify! It is possible to implement something that you could call bidirectionalBinding, but thats not what you want to do using plain javascript! It would mean implementing eventListeners on your textValue etc.

CodeFanatic
  • 11,434
  • 1
  • 20
  • 38
1

Javascript allows the creation of object "properties" where reading or writing can execute user-defined code.

What you can do is creating the HTML node and a Javascript object with a property so that when you write to the property the code updates the HTML node:

var d = document.createElement("div");
document.body.appendChild(d);
var obj = {get value()  { return d.textContent; },
           set value(x) { d.textContent = x; }};
obj.value = "foo"; // Will also update d content

Note that a property that allows writing needs a place where to store the data... in the above I used directly d.textContent so the two are actually synchronized (changing obj.value changes the DOM node and vice versa).

6502
  • 112,025
  • 15
  • 165
  • 265