普通Javascript双向数据绑定

fat*_*fat 14 javascript data-binding jquery

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

我很幸运能找到一个很好的答案来解决我的一半问题@ stackoverflow导致我这个要点https://gist.github.com/384583,但我仍然无法完成100%的事情.

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

如果您尝试运行小提琴并单击"视图值",您将得到未定义,而我想获取对象属性的实际值.

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

免责声明:正如我所说,我这样做是因为我想要更好的javascript知识,我不会写我的框架.所以任何"USE FRAMEWORK X"都是完全没用的,因为我可以用angularjs完成工作.

met*_*ngs 5

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

我在Object.prototype .__ watch中更新了重新定义的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
});
Run Code Online (Sandbox Code Playgroud)

目前的HTML:

<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>
Run Code Online (Sandbox Code Playgroud)