agility icon indicating copy to clipboard operation
agility copied to clipboard

2-in-1 for input data-bind

Open Wizek opened this issue 12 years ago • 2 comments

Feature request #1: If type isn't present on input element, default to type="text" Feature request #2: Instant data binding should't be bound to only type="search", but accessible on other types too!

Wizek avatar Jan 10 '12 21:01 Wizek

thanks @Wizek, #1 makes sense to me since that seems to be the expected HTML behavior.

As far as #2...

To me it looks like the only other types this would apply to would be input[type="text"] and textarea. I don't think it should be a default behavior because of all the events flying around as a consequence, but perhaps a toggle if one wants it. @arturadib thoughts?

My suggestion for implementation would be along the lines of adding an options data-bind-instant=true and doing something like below around https://github.com/arturadib/agility/blob/master/agility.js#L564:

// <input type="text"> and <textarea>: 2-way binding
else if ($node.is('input[type="text"], textarea')) {
  // Model --> DOM
  self.bind('_change:'+bindData.key, function(){
    $node.val(self.model.get(bindData.key)); // this won't fire a DOM 'change' event, saving us from an infinite event loop (Model <--> DOM)
  });            
  // Model <-- DOM
  if ( $node.data( 'bind-instant' ) == true ) {
    $node.keypress(function(){
      // Without timeout $node.val() misses the last entered character
      setTimeout(function(){
        var obj = {};
        obj[bindData.key] = $node.val();
        self.model.set(obj); // not silent as user might be listening to change events
      }, 50);
    });
  } // instant bind
  else { // efficient bind
    $node.change(function(){
      var obj = {};
      obj[bindData.key] = $(this).val();
      self.model.set(obj); // not silent as user might be listening to change events
    });
  }
  // 1-way attribute binding
  bindAttributesOneWay();
}

tristanls avatar Jan 11 '12 20:01 tristanls

@tristanls Does $node.val() also miss the last entered character if you bind for the keyup event (instead of keypress)? I hope it can be done more elegantly without setTimeout.

Wizek avatar Jan 12 '12 11:01 Wizek