当前位置: 首页 > 知识库问答 >
问题:

纯Javascript双向数据绑定

梁丘俊材
2023-03-14

出于好奇和增加知识,我想在dom元素和javascript变量之间实现某种双向数据绑定。

我很幸运,在这里@stackoverflow找到了一个很好的答案,解决了我一半的问题,这就引出了这个要点https://gist.github.com/384583,但我仍然无法100%完成这件事。

下面是我的代码示例:http://jsfiddle.net/bpH6Z/

如果您尝试运行fiddle并单击“查看值”,您将得到未定义的值,而我希望获得对象属性的实际值。

由于缺乏javascript经验,我可能做错了什么,但是你知道为什么在调用_bind()和_watch()之后我不能正确读取属性“secret”吗?

免责声明:正如我所说,我这样做是因为我想更好地了解javascript,我不打算写我的框架。所以任何"USE FRAMEWORK X"是完全无用的,因为我可以用angularjs完成工作。

共有3个答案

夏才
2023-03-14

我为多个观察者增强了它。

http://jsfiddle.net/liyuankui/54vE4/

//The dom element changes values when the propertyName is setted
this._watch = function(DOMelement, propertyName) {
    //__watch triggers when the property changes
    if(watchList.indexOf(DOMelement)<0){
        watchList.push(DOMelement);
    }
    this.__watch(propertyName, function(property, value) {
        for(var i=0;i<watchList.length;i++){
            var watch=watchList[i];
            $(watch).val(value);
            $(watch).html(value);
        }
    });
};
刘昌翰
2023-03-14

传递给\u watch函数的处理程序缺少return语句。

this._watch = function(DOMelement, propertyName) {
    //__watch triggers when the property changes
    this.__watch(propertyName, function(property, value) {
        $(DOMelement).val(value);
        return value;
    })

}

因为newval设置为从处理程序返回的内容,如果没有它,它将是未定义的。

裴实
2023-03-14

请试试http://jsfiddle.net/bpH6Z/4/

我已经更新了对象中重新定义的getter/setter。原型__注意,当前处理程序还需要返回新值。

更新:现在不需要处理程序返回新设置的值。

当前代码

//Got this great piece of code from https://gist.github.com/384583
Object.defineProperty(Object.prototype, "__watch", {
    enumerable: false,
    configurable: true,
    writable: false,
    value: function(prop, handler) {
        var val = this[prop],
            getter = function() {
                return val;
            },
            setter = function(newval) {
                val = newval;
                handler.call(this, prop, newval);
                return newval;
            };

        if (delete this[prop]) { // can't watch constants
            Object.defineProperty(this, prop, {
                get: getter,
                set: setter,
                enumerable: true,
                configurable: true
            });
        }
    }
});

var Controller = function () {
    //The property is changed whenever the dom element changes value
    //TODO add a callback ?
    this._bind = function (DOMelement, propertyName) {
        //The next line is commented because priority is given to the model
        //this[propertyName] = $(DOMelement).val();
        var _ctrl = this;
        $(DOMelement).on("change input propertyChange", function(e) {
            e.preventDefault();
            _ctrl[propertyName] = DOMelement.val();
        });

    };

    //The dom element changes values when the propertyName is setted
    this._watch = function(DOMelement, propertyName) {
        //__watch triggers when the property changes
        this.__watch(propertyName, function(property, value) {
            $(DOMelement).val(value);
        });
    };
};

var ctrl = new Controller();
ctrl.secret = 'null';
ctrl._bind($('#text1'), 'secret'); // I want the model to reflect changes in #text1
ctrl._watch($('#text2'), 'secret'); // I want the dom element #text2 to reflect changes in the model
$('#button1').click(function() {
    $('#output').html('Secret is : ' + ctrl.secret); //This gives problems
});

当前超文本标记语言:

<html>
<head></head>
<body>
    value: <input type="text" id="text1" /><br />
    copy: <input type="text" id="text2" /><br />
    <input type="button" id="button1" value="View value"><br />
    <span id="output"></span>
</body>
</html>
 类似资料:
  • 1. 前言 本小节我们将介绍 Vue 中数据的双向绑定指令 v-model。v-model 的学习相对简单 我们可以用 v-model 指令在表单 、 及 元素上创建双向数据绑定。它会根据控件类型自动选取正确的方法来更新元素。它负责监听用户的输入事件以更新数据,并对一些极端场景进行一些特殊处理。 2. 慕课解释 用 v-model 指令在表单 、 及 元素上创建双向数据绑定。它会根据控件类型自动选

  • 本文向大家介绍Vue实现双向数据绑定,包括了Vue实现双向数据绑定的使用技巧和注意事项,需要的朋友参考一下 Vue实现双向数据绑定的方式,具体内容如下 Vue是如何实现双向数据绑定的呢?答案是前端数据劫持。其通过Object.defineProperty()方法,这个方法可以设置getter和setter函数,在setter函数中,就可以监听到数据的变化,从而更新绑定的元素的值。 实现对象属性变化

  • 本文向大家介绍Nuxt.js 数据双向绑定的实现,包括了Nuxt.js 数据双向绑定的实现的使用技巧和注意事项,需要的朋友参考一下 假定我们有一个需求,一开始通过mounted()将一个字符串渲染在页面上,但是我们经过操作后修改了数据并且需要将得到的结果重新异步渲染到页面中去,而不是跳转刷新页面来重新渲染 首先模板中data()中定义数据,并且要将定义的数据显示出来 然后我们通过methods里的

  • Mpx针对表单组件提供了wx:model双向绑定指令,类似于v-model,该指令是一个语法糖指令,监听了组件抛出的输入事件并对绑定的数据进行更新,默认情况下会监听表单组件的input事件,并将event.detail.value中的数据更新到组件的value属性上。 简单实用示例如下: <view> <input type="text" wx:model="{{message}}"> <

  • 双向绑定这个概念在angular出现的时候,就作为王牌概念. 现在几乎是个js前端框架,就有这个功能. 它的概念是: 某个变量, 如果展现在页面上的话: 如果在代码层面进行修改, 那么页面的值就会发生变化 如果在页面进行修改(例如在input标签中), 那么代码的值就会发生变化. 一个演示例子. 在我们的项目中,增加一个 vue页面: src/components/TwoWayBinding.vu