除了缺乏完整的框架,如角,淘汰机等,谁能推荐一个简单的数据绑定jQuery插件吗?
购物车需要一个页面应用程序,它需要在ajax完成后更新页面上的某些元素。只需要遍历字段并更新用户界面。
是的,我知道我可以自己写一些东西,但如果已经有什么东西存在的话,我不想重新发明轮子。
我的研究把我引向了jquery.bindings --但它并不受欢迎(只有一个贡献者)
有什么建议吗?
发布于 2014-10-10 07:07:35
调查rivets.js。
铆钉是一个轻量级的(3.4kb小型化和gzipped)和强大的数据绑定和模板库。
Rivets.js完全不了解您的模型/控制器层,并且可以很好地处理使用事件驱动模型(如Backbone.js和Stapes.js )的现有库。它附带了一个内置适配器,用于使用ES5本机订阅普通JS对象,但是可以用Watch.JS适配器或Object.observe适配器替换。 的一些特性,您可以从Rivets.js中获得现成的信息:
铆钉采用基于DOM的模板系统
Rivets.js没有解析模板字符串并将其编译成HTML,而是直接将模型连接到DOM的现有部分,这些部分包含绑定声明和直接控制DOM节点上的流指令。在绑定到父DOM节点时,只需传递模型,其余部分由Rivets.js处理。
简而言之,假设您希望在产品对象中显示数据,如下所示:
var productInfo= {
name: "test",
price: 1000
}在以下HTML中:
<ul id="product">
<li>Name</li>
<li>Price</li>
</ul>您可以使用铆钉绑定数据,例如:
rivets.bind($('#product'), {
product: productInfo // product will be the alias name inside HTML template
});相应的铆钉模板如下:
<ul id="product">
<li rv-text="product.name"></li>
<li v-text="product.price"></li>
</ul>或者更多的语义
<ul id="product">
<li data-rv-text="product.name"></li>
<li data-rv-text="product.price"></li>
</ul>rivets.bind方法接受模板元素、模型数据以及您希望从主铆钉对象覆盖的任何选项(可选)
或者,如果要绑定产品对象数组,则为:
rivets.bind($('#product'), {
product: ProductArray // where productArray is an array of products
});您可以使用rv-each使用迭代绑定,如:
<ul class="products" data-rv-each-product="products">
<li data-rv-text="product.name"></li>
<li data-rv-text="product.price"></li>
</ul>铆钉将根据数组中的项目创建n数量的列表。
您可以在指南中找到更多很酷的特性。
发布于 2014-10-10 06:00:44
只要您与类名和返回的JSON字段名保持一致,就可以用下面的代码更新数据(注意:我没有测试这段代码)。希望这能有所帮助。我找不到任何的jQuery插件,除了你找到的一个做你想要的。
$.ajax({
url: "/GetCart",
type: "GET",
dataType: "json",
success: function (response) {
var r = jQuery.parseJSON(response);
$.each(r, function(key,value) {
if (jQuery.type(value) == "string") {
$('.'+key).html(value);
}
else if (jQuery.type(value) == "array") {
$.each(value, function(aindex,avalue) {
$.each(avalue, function(ikey,ivalue) {
$('.'+ikey.toString())[aindex].html(ivalue);
}
}
}
}
}
});假设GetCart返回以下JSON对象:
{ 'firstname': 'Bob', 'lastname': 'Ross', 'items': [ { 'desc' : 'car', 'quantity': 1, 'price': 15000.00}, { 'desc' : 'tire', 'quantity': 4, 'price': 200.00} ] }还假设您有以下HTML
<form>
Firstname: <span class="firstname"> </span><br />
Lastname: <span class="lastname"> </span><br />
Items:<br />
<table>
<tr><th>Description</th><th>Quantity</th><th>Price</th></tr>
<tr><td class="desc"> </td><td class="quantity"> </td><td class="price"> </td></tr>
<tr><td class="desc"> </td><td class="quantity"> </td><td class="price"> </td></tr>
</table
</form>https://stackoverflow.com/questions/26245822
复制相似问题