Search code examples
javascriptractivejs

Ractive, two bindings on an <input>


Note: I'm not referring to "two way binding"

I'm using a ractive decorator (select2) to transform an input into a select2. The data I obtain through ajax are some records from the database, example:

[{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"}]

I format these object using select2's functions, formatResult and formatSelection

The element on which I'm using the decorator is something like this:

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

After the user select something, values will be equal to the ids of the selected object, (eg: values=1,3 if i select the first and the last records)

My question is: how can i obtain the full object that was selected? I was thinking about two bindings on the <input> (<input value="{{values}}" data-objects="{{objects}}"> so the decorator can save the full objects too, when the user select something. But when i debug the decorator, node._ractive.binding only shows value and not other attributes.


Solution

  • I solved it by saving the result of the ajax request in ractive, then matching the ids with the object ids to find the original objects.

    Not the prettiest thing, but it works.

    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>