简体   繁体   中英

HTML content with reference to javascript object attrtibute

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.

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.

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM