gpt4 book ai didi

javascript - Ajax数据双向数据绑定(bind)策略?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:07:43 24 4
gpt4 key购买 nike

我愿意1) 绘制创建表单字段并使用来自 javascript 对象的数据填充它们2) 每当表单字段的值发生变化时更新那些支持对象

第 1 条很简单。我有几个 js 模板系统,我一直在很好地使用它们。

第 2 个可能需要一些思考。在谷歌上快速搜索“ajax 数据绑定(bind)”,发现了一些看起来基本上是单向的系统。它们旨在更新基于支持 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);

最佳答案

有大量的库可以实现你想要的。

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

希望对您有所帮助!

关于javascript - Ajax数据双向数据绑定(bind)策略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2303410/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com