-1

我可能没有使用正确的术语。我想要实现的是在 javascript 中“镜像”或“同步”一个变量。我有以下代码:

class myClass {
    constructor(elem) {
        this.text = elem.innerText;
    }
}

这不会改变innerText. elem我将如何配置变量 [s] 以使它们相互“镜像”?

PS我很难在谷歌上搜索这个,因为我不知道我想要达到的目标。

4

3 回答 3

0

您想要的称为数据绑定。Javascript 中的变量本身并不是这样操作的。您必须使用 getter/setter 方法包​​装它们。

所以它看起来像这样的东西:

var myElem = Sizzle("#myElem");

mirror('myVar', function(myVar){
    myElem.innerText = myVar;
});

mirror('myVar', 'foo');

镜像的实现如下所示:

var __data__ = {};
var __bindings__ = {};
function mirror(name, value){
    // if no value is passed in
    // get the existing value
    if(!value){
        return __data__[name];
    }

    // if the "value" is a function
    // register it to the list of
    // functions that get called when
    // the value changes. Also known
    // as a listener.
    if(typeof value == 'function'){
        var func = value;

        // if there's no existing list
        // for this value, create one
        if(!__bindings__[name]){
            __bindings__ = [];
        }

        // if the data already exists
        // go ahead and fire this function
        // immediately
        if(__data__.hasOwnProperty(name)){
            func(__data__[name]);
        }

        __bindings__[name].push(func);
        return;
    }

    // if we've made it this far, we're setting
    // the value of our variable
    __data__[name] = value;

    // if there's a list of functions (listeners)
    // call each of them passing in the value that
    // we just set
    if(__bindings__.hasOwnProperty(name)){
        __bindings__[name].forEach(function(func){
            func(__data__[name]);
        });
    }
}
于 2015-04-26T12:02:21.577 回答
0

在 js 中,就像在其他程序语言中一样,分配原始类型变量,不会创建对它的引用。所以你可能会写这个来设置innerHTML:

var myElem = Sizzle("#myElem");
myElem.innerText = "foo";
于 2015-04-26T12:04:10.933 回答
0
var myElem = Sizzle("#myElem");
var obj = {
    set myVar(text) {
        myElem.innerText = text;
    },
    get myVar() {
        return myElem.innerText;
    }
};
obj.myVar = "foo";

您可以使用settersgetters,但您需要绑定变量位于对象内。

编辑:

从技术上讲,即使是全局变量也属于window对象,所以这应该有效:

var myElem = Sizzle("#myElem");
Object.defineProperty(window, 'myVar', {
    set: function(text) {
        myElem.innerText = text;
    },
    get: function() {
        return myElem.innerText;
    }
});
myVar = "foo";  // works assuming that we are using global scope
                // i.e. myVar isn't overridden in local scope
window.myVar = "foo"; // will work regardless

更新:

问题已更改,因此这是更新的答案:

class myClass {
    constructor(elem) {
        Object.defineProperty(this, 'text', {
            set: function(text) {
                elem.innerText = text;
            },
            get: function() {
                return elem.innerText;
            }
        });
    }
}
于 2015-04-26T12:06:18.897 回答