0

I'm trying to figure out how browsers do the DOM update job when javascript changes the Node.innerHTML property.

Given the code:

> var obj=document.createElement("DIV");
> obj.innerHTML='<P><SPAN>A</SPAN></P><DIV>B</DIV>';
> obj.childNodes
[<p>​<span>​A​</span>​</p>​, <div>​B​</div>​]

It seems to be magic for me, since I think that innerHTML is a property, not a function, so...

How javascript can be notified of changes in a field to call a function to update the DOM tree ?

Is There any type of listener for call a function when a variable is changed in javascript, or only some daemon monitor Node.innerHTML variables on each javascript line executed ?

If you wonder why it matter, I'm writing a DOMParser and this is a issue for me.

Using the given references, I understood that browser engine may provide ways like Object.watch (gecko) or Object.observe(chrome).

But there is a way to do it in nodejs ?

ton
  • 2,505
  • 1
  • 29
  • 31
  • properties, functions,... that's all just names. – njzk2 Jan 22 '15 at 18:58
  • other example: `a = []; a[1] = 2; a.length;` output is 2, but no function was called, so how does the array knows to change the value of length? – njzk2 Jan 22 '15 at 19:00
  • possible duplicate of [javascript event listener for changes in an object variable](http://stackoverflow.com/questions/5860218/javascript-event-listener-for-changes-in-an-object-variable) – njzk2 Jan 22 '15 at 19:01
  • There's no guarantee that `Node` can be implemented in javascript. – recursive Jan 22 '15 at 19:03
  • 1
    you can use Object.defineProperty to create these "do stuff upon setting" routines, known as getters and setters. – dandavis Jan 22 '15 at 19:31
  • @dandavis, It's exactly what I'm looking for... thank you. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty – ton Jan 22 '15 at 19:51

1 Answers1

2

since I think that innerHTML is a property, not a function

Javascript supports setters. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set

Before this became part of the language standard native objects (such as DOM Nodes) already used setter functionality internally.

the8472
  • 35,110
  • 4
  • 54
  • 107
  • And even if it didn't (as it used to not) it doesn't matter because most of the DOM element is written in C (or some other language) and just given a JavaScript interface. – Quentin Jan 22 '15 at 19:54
  • should also mention ODP, since the setter syntax only works on object literals, and custom Element models are not likely to be defined via literals. also worth mentioning for node.js is Object.prototype.__defineSetter__ – dandavis Jan 23 '15 at 18:45