1

Is there a way in javascript to make this work?

// define an user class
var User = function (name) {
    this.name = name;
}

// create an user object
var user = new User('John');

var anchor = document.createElement('a');

anchor.innerHTML = user.name;
// add the anchor to DOM
document.body.appendChild(anchor);

// change the user name
user.name = 'James';

After this, the html of the anchor changes the content automatically because its holds a reference to object user. Maybe this sounds dumb, but what I thinking is if is there a way to DOM watch any changes on its values through object reference.

Many thanks.

3 Answers 3

1

This will not work. You need to update the innerHTML manually to reflect the value. You can use clever frameworks like AngularJS for this to taken this manual action away.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, I thought about angular, it's a good choice. But I was trying to figure out a solution without an entire framework, thinking about a quick solution with pure javascript, but seems there is no way out. Thanks for your answer.
1

You can't use the DOM to watch for this because you are looking for when a property of an object changes.

You can watch for that by using a property with a setter function instead of a plain one.

// define an user class
function User(name) {
  this._name = name;
}

// Add some functions to watch variables and play with the DOM

Object.defineProperties(User.prototype, {
  add_to_dom: {
    value: function add_to_dom(parent_element) {
      this._parent_element = parent_element;
      this._text_node = document.createTextNode("");
      this._parent_element.appendChild(this._text_node);
      this.update_dom();
    }
  },
  update_dom: {
    value: function update_dom() {
      this._text_node.data = this._name;
    }
  },
  name: {
    get: function() {
      return this._name;
    },
    set: function(name) {
      this._name = name;
      this.update_dom();
    }
  }
});



// create an user object
var user = new User('John');
var anchor = document.createElement('a');
document.body.appendChild(anchor);
user.add_to_dom(anchor);

// change the user name
user.name = 'James';

For larger scale approaches, you might want to look into tools like React.

1 Comment

Thanks for your answer. This is a good solution, but as you and Bas Slagter said, the best choice would use a tool that do it for me, since there is no quick solution.
-1

You have to make seomthing like MVC (Model, View Control)

Your user class ist the Model Your HTML Element is a view What you need is a controller, which controls the changing of the value

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.