简体   繁体   English

引用javascript对象属性的HTML内容

[英]HTML content with reference to javascript object attrtibute

Is there a way in javascript to make this work? 有没有一种方法可以使这项工作在javascript中?

// 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. 此后,锚点的html会自动更改内容,因为它包含对对象用户的引用。 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. 也许这听起来有些愚蠢,但是我的想法是,是否有一种方法可以通过对象引用监视DOM值的任何变化。

Many thanks. 非常感谢。

This will not work. 这是行不通的。 You need to update the innerHTML manually to reflect the value. 您需要手动更新innerHTML以反映该值。 You can use clever frameworks like AngularJS for this to taken this manual action away. 您可以使用诸如AngularJS之类的聪明框架来取消此手动操作。

You can't use the DOM to watch for this because you are looking for when a property of an object changes. 您无法使用DOM来监视它,因为您正在寻找对象的属性何时发生变化。

You can watch for that by using a property with a setter function instead of a plain one. 您可以通过使用带有setter函数的属性而不是普通属性来进行监视。

 // 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 . 对于更大规模的方法,您可能需要研究React等工具。

You have to make seomthing like MVC (Model, View Control) 您必须像MVC一样制作模型(模型,视图控件)

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 您的用户类别是模型HTML元素是视图您需要的是一个控制器,它控制值的更改

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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