Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: two way filters #67

Open
cosmoKenney opened this issue Jun 27, 2017 · 3 comments
Open

Feature request: two way filters #67

cosmoKenney opened this issue Jun 27, 2017 · 3 comments

Comments

@cosmoKenney
Copy link

cosmoKenney commented Jun 27, 2017

Looks like this library isn't getting much updates, but I think it would be cool to have two way filters.
I.e. a phone filter would take a 10 digit value like "1234567890" and convert it to "(123) 456-7890" as the value is being sent to the view. And then strips the formatting upon return the view-model.

I could see enabling this by adding an object the ko.filters object:

ko.filters.phone {
    read: function ( phoneOut ) { return phoneOut ? phoneOut.replace( /(\d{3})(\d{3})(\d{4})/, "($1) $2-$3" ) : ''; }
    write: function ( phoneIn ) { return (phoneIn || '').replace( /[^\d]/g, '' ); }
};

Could this somehow be wrapped in an computed prior to binding?

Update: copy and paste fixed.

Update again:
And this would, obviously, be used like this:

<input value="{{CellPhone | phone}}" />
@mbest
Copy link
Owner

mbest commented Jun 27, 2017

That's an interesting idea, but it could be done today by returning a computed.

ko.filters.phone = function (value) {
    return ko.pureComputed({
        read: function () {
            return (ko.unwrap(value) || '').replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
        },
        write: function (phoneIn) {
            value((phoneIn || '').replace(/[^\d]/g, '');
        }
    });
};

@cosmoKenney
Copy link
Author

Oh, perfect. For some reason I was thinking a filter could only return text. The computed solution is way cool.

@mbest
Copy link
Owner

mbest commented Jun 28, 2017

I didn't actually test it, so let me know if you run into any problems. This actually isn't best practice in terms of performance because the computed will be re-created each time the value changes, but I'm not sure if there's another way to do it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants