Ajax数据双向数据绑定策略?

时间:2010-02-20 19:38:21

标签: javascript ajax data-binding

我想 1)绘制创建表单字段并使用来自javascript对象的数据填充它们 2)只要表单字段的值发生变化,就更新这些后备对象

1号很容易。我有一些js模板系统,我一直在使用它非常好。

2号可能需要一些思考。关于“ajax数据绑定”的快速谷歌搜索出现了几个基本上是单向的系统。它们旨在基于支持js对象更新UI,但似乎没有解决在对​​UI进行更改时如何更新这些支持对象的问题。任何人都可以推荐任何能为我这样做的图书馆吗?这是我可以自己写的东西,没有太多麻烦,但如果已经考虑过这个问题,我宁愿不重复这项工作。

//////////////////////编辑/////////////////

我已经创建了自己的jquery插件来完成此任务。这里是。请告诉我它是否有用,如果你认为它可能值得更“官方”。如果您有任何问题或疑问,也请告诉我。

/*

    Takes a jquery object and binds its form elements with a backing javascript object. Takes two arguments: the object 
    to be bound to, and an optional "changeListener", which must implement a "changeHappened" method.

    Example: 

    // ============================
    // =     backing object       =
    // ============================

    demoBean = {
        prop1 : "val",
        prop2 : [
            {nestedObjProp:"val"},
            {nestedObjProp:"val"}
        ],
        prop3 : [
            "stringVal1",
            "stringVal12"
        ]
    }

    // ===========================
    // =        FORM FIELD       =
    // ===========================

    <input class="bindable" name="prop2[1].nestedObjProp">


    // ===========================
    // =       INVOCATION        =
    // ===========================

    $jq(".bindable").bindData( 
        demoBean, 
        {changeHappened: function(){console.log("change")}}
    )


*/


(function($){


    // returns the value of the property found at the given path
    // plus a function you can use to set that property
    var navigateObject = function(parentObj, pathArg){
        var immediateParent = parentObj;
        var path = pathArg
            .replace("[", ".")
            .replace("]", "")
            .replace("].", ".")
            .split(".");
        for(var i=0; i< (path.length-1); i++){
            var currentPathKey = path[i];
            immediateParent = immediateParent[currentPathKey];
            if(immediateParent === null){
                throw new Error("bindData plugin encountered a null value at  " + path[i] + " in path" + path);
            }
        }

        return {
            value: immediateParent[path[path.length - 1]],
            set: function(val){
                immediateParent[path[path.length - 1]] = val
            },
            deleteObj: function(){
                if($.isArray(immediateParent)){
                    immediateParent.splice(path[path.length - 1], 1);
                }else{
                    delete  immediateParent[path[path.length - 1]];
                }
            } 
        }

    }

    var isEmpty = function(str){
        return str == null || str == "";
    }

    var bindData = function(parentObj, changeListener){

        var parentObj,
            radioButtons = [];
        var changeListener;
        var settings;
        var defaultSettings = {
            // if this flag is true, you can put a label in a field,
            // like <input value="Phone Number"/>, and the value
            // won't be replaced by a blank value in the parentObj
            // Additionally, if the user clicks on the field, the field will be cleared.
            allowLabelsInfields: true 
        };

        // allow two forms: 
        // function(parentObj, changeListener)
        // and function(settings). 
        if(arguments.length == 2){
            parentObj = arguments[0];
            changeListener = arguments[1]
            settings = defaultSettings;
        }else{  
            settings = $jq.extend(defaultSettings, arguments[0]);
            parentObj = settings.parentObj;
            changeListener = settings.changeListener;
        }

        var changeHappened = function(){};
        if(typeof changeListener != "undefined"){
            if(typeof changeListener.changeHappened == "function"){
                changeHappened = changeListener.changeHappened;
            }else{
                throw new Error("A changeListener must have a method called 'changeHappened'.");
            }
        };
        this.each(function(key,val){
            var formElem = $(val);
            var tagName = formElem.attr("tagName").toLowerCase();
            var fieldType;
          if(tagName == "input"){
            fieldType = formElem.attr("type").toLowerCase();
          }else{
            fieldType = tagName;
          }


            // Use the "name" attribute as the address of the property we want to bind to.
            // Except if it's a radio button, in which case, use the "value" because "name" is the name of the group
            // This should work for arbitrarily deeply nested data. 
            var navigationResult = navigateObject(parentObj, formElem.attr(fieldType === "radio"? "value" : "name"));

            // populate the field with the data in the backing object

            switch(fieldType){

        // is it a radio button? If so, check it or not based on the 
        // boolean value of navigationResult.value
        case "radio":
          radioButtons.push(formElem);
          formElem.data("bindDataPlugin", {navigationResult: navigationResult});
          formElem.attr("checked", navigationResult.value);
          formElem.change(function(){
            // Radio buttons only seem to update when _selected_, not 
            // when deselected. So if one is clicked, update the bound
            // object for all of them. I know it's a little ugly,
            // but it works.
            $jq.each(radioButtons, function(index, button){
              var butt = $jq(button);
              butt.data("bindDataPlugin").navigationResult.set(butt.attr("checked"));
            });
            navigationResult.set(formElem.attr("checked"));           
            changeHappened();
          });
          break;

        case "text":
          // if useFieldLabel is true, it means that the field is 
          // self-labeling. For example, an email field whose 
          // default value is "Enter Email".
          var useFieldLabel = isEmpty( navigationResult.value )
                   && !isEmpty( formElem.val() )  
                   && settings.allowLabelsInfields;
          if(useFieldLabel){
           var labelText = formElem.val();
           formElem.click(function(){
             if(formElem.val() === labelText){
               formElem.val("");
             }
           })
          }else{
           formElem.attr("value", navigationResult.value);
          }
          formElem.keyup(function(){
           navigationResult.set(formElem.attr("value"));
           changeHappened();
          });

          break;

        case "select":
          var domElem = formElem.get(0);
                $jq.each(domElem.options, function(index, option){
                    if(option.value === navigationResult.value){
                        domElem.selectedIndex = index;
                    }
                });
                formElem.change(function(){
                    navigationResult.set(formElem.val());
                })
          break;

        case "textarea":
          formElem.text(navigationResult.value);
          formElem.keyup(function(){
           changeHappened();
           navigationResult.set(formElem.val());
          });
          break;
      }


        });
        return this;
    };

    bindData.navigateObject = navigateObject;

    $.fn.bindData = bindData;

})(jQuery);

3 个答案:

答案 0 :(得分:2)

有很多图书馆可以实现你想要的目标。

对于初学者,您可以使用DWR来获取Ajax功能。为表单字段的onChange事件触发的方法应该对相应的后备对象进行DWR调用

希望这有帮助!

答案 1 :(得分:1)

Microsoft提出了对jQuery核心进行增强的建议,​​该核心实现了适当的数据绑定,包括两个绑定(源到目标,目标到源)。

他们称之为数据链接 - 这很奇怪,因为在所有其他MS技术(WinForms,WPF,WebForms等)中这个概念的名称是 DataBinding

Link to the MS Proposal

答案 2 :(得分:0)

DataBind - jQuery的模板插件。该库有一个方法unbinddata(),它将数据收集回json-array。

不幸的是,该库只适用于表单输入。

如果你做了一些解决方案,我能看到吗?