Backbone.ModelBinder icon indicating copy to clipboard operation
Backbone.ModelBinder copied to clipboard

Change ViewToModel value based on input focus

Open adammorris opened this issue 10 years ago • 1 comments

Hi,

Trying to use ModelBinder to change the input value when editing to the actual value stored in the model, and then revert to a display value when done editing.

For example, I want to display a pretty sales number in thousands, with a dollar sign, like "$2.1k", but when I click the input box to edit it, have the model's actual value display as "2095.3"

My best luck has been in modifying a custom converter to check if the target el is in focus or not... but under some circumstances, when leaving the input box, the ViewToModel is called after ModelToView is updated, causing issues. Not sure if I'm using it right, or just totally going in the wrong direction.

Any ideas on what a better way might be?

Here is a fiddle - http://jsfiddle.net/amorris/JJezD/

  salesConverter: function(direction, value, attribute, model, boundEls) {
    if (direction === 'ViewToModel') {
      if ($(boundEls).is(":focus")) {
        return model.get(attribute);
      } else {
        return value;
      }
    } else {
      if ($(boundEls).is(":focus")) {
        return value;
      } else {
        return '$' + (value / 1000).toFixed(1).toString() + 'k';
      }
    }
  }

 ...

bindings = {
 sales: [{selector: '[name=sales]', converter: this.salesConverter}, ... ]
}

this.modelBinder.bind(this.model, $(this.el), bindings, {changeTriggers: {'': 'change click focusout'}})

adammorris avatar Apr 15 '14 17:04 adammorris

@adammorris Yeah, that solution looks pretty close to what I do in that situation...

// If you do this kind of thing globally you could also set changeTriggers via Backbone.ModelBinder.SetOptions( ... );
// Here I don't want the focus events unless I have a <input type="text"..
this._modelBinder.bind(this.model, this.el, bindings, {changeTriggers: {'': 'change', ':text': 'focus focusout'}});

// and here is a converter example
                      converter: function(dir, val, att, model, boundEls){
                            if (dir === 'ViewToModel') {
                                return val.replace('$', '');
                            }
                            else {
                                if($(boundEls).is(':focus')) {
                                    return '$' + val;
                                }
                                else {
                                    return val;
                                }
                            }

So, I see the "$" symbol when I start editing the field.

theironcook avatar Apr 17 '14 22:04 theironcook