反应式,<输入>上的两个绑定

Ractive, two bindings on an <input>

本文关键字:两个 绑定 输入 反应式      更新时间:2023-09-26

注意:我不是指"双向绑定">

我正在使用反应式装饰器 (select2( 将输入转换为 select2。我通过 ajax 获得的数据是数据库中的一些记录,例如:

[{id:1, name:"test", quantity:2, image:"image.jpg"}, 
{id:2, name:"bar", quantity:21, image:"image2.jpg"}, 
{id:3, name:"foo", quantity:21, image:"image3.jpg"}]

我使用 select2 的函数格式化这些对象,formatResultformatSelection

我使用装饰器的元素是这样的:

<input type="hidden" value="{{values}}" decorator="select2">

用户选择某些内容后,values将等于所选对象的 id,(例如:如果我选择第一个和最后一个记录,则值 = 1,3(

我的问题是:如何获取所选的完整对象?我在考虑<input>上的两个绑定(<input value="{{values}}" data-objects="{{objects}}">这样装饰器也可以在用户选择某些内容时保存完整的对象。但是当我调试装饰器时,node._ractive.binding只显示值而不显示其他属性。

我通过将 ajax 请求的结果保存在 ractive 中,然后将 id 与对象 id 匹配以查找原始对象来解决它。

不是最漂亮的东西,但它有效。

Ractive.decorators.select2.type.whatever = {
    tags: [],
    separator: "|",
    ajax: {
      url: "ajax_url",
      data: function(searchterm, page) {
        return {
          searchterm: searchterm,
          page: page,
        };
      },
      results: function(data, page) {
        //Here i save the records
        ractive.set("data", data.records);
        return {results: data.records, more: data.more};
      }
   }
};
var ractive = new Ractive({
  el: "things",
  template: "template",
});
ractive.observe("ids", function(ids) {
  var data = ractive.get("data");
  ids = ids.split("|");
  
  //I can obtain the original objects
});
<script src="http://cdn.ractivejs.org/latest/ractive.js"></script>
<script src="https://rawgit.com/Prezent/ractive-decorators-select2/master/ractive-decorators-select2.js"></script>
<!-- select2, jquery missing -->
<script type="ractive-template" id="template">
  <input type="hidden" value="{{ids}}" decorator="select:whatever">
</script>
<div id="things"></div>