patrick-steele-idem / morphdom

Fast and lightweight DOM diffing/patching (no virtual DOM needed)
MIT License
3.21k stars 129 forks source link

Enhancement: Option to keep values #16

Closed oppianmatt closed 9 years ago

oppianmatt commented 9 years ago

When updating the dom sometimes we want to keep existing input values. Would be handy to have an option that kept the existing 'value' attribute and only override it if a new one is in the new dom.

oppianmatt commented 9 years ago

actually with the hooks you've provided can implement this myself. So if anyone else wants to know, this is how:

                morphdom($(i)[0], s, {
                  onBeforeMorphEl: function(fromEl, toEl) {
                    var val = $(fromEl).val();
                    if (val) {
                      console.log("Found val: " + val);
                      $(toEl).val(val);
                    }
                  }}
                );
patrick-steele-idem commented 9 years ago

Nice trick! Thanks for sharing

Personally, I don't think jQuery is adding much value for that use case and would go with something more similar to the following (especially since onBeforeMorphEl may be called many times):

morphdom($(i)[0], s, {
    onBeforeMorphEl: function(fromEl, toEl) {
        if (toEl.tagName === 'INPUT') {
            toEl.value = fromEl.value;
        }
    }
});
oppianmatt commented 9 years ago

Thanks. I am trying to move away from jquery. But unfortunatly I used it to expand on this and have it also move over selected/checked states using the jquery pseudo selectors:

$toEl.prop( "checked", $fromEl.is(':checked') );
$toEl.prop( "selected", $fromEl.is(':selected') );

But I suppose I could use .selected and .checked although I don't know how cross browser it will be.

patrick-steele-idem commented 9 years ago

el.checked is definitely cross browser. MDN is probably the best choice for knowing which properties are standard. For example, for an HTML input element: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement

Unless there is a note next to the property or a note in the Browser compatibility section then you can consider it safe to use.

I hope that helps.