Validating and resetting a property in the View

2 posts, 0 answers
  1. John DeVight
    John DeVight avatar
    209 posts
    Member since:
    Jan 2010

    Posted 24 Oct 2012 Link to this post

    I have a view with an input field that displays firstName.  I want to apply some business logic to firstName.  If the user violates the business logic, I want the view to display the "current" value for firstName.
    .
    Here is the view:
    <div id="personFields">
        <div class="field">
            <div>First Name:</div><input data-bind="value: firstName" required />
        </div>
        <div class="field">
            <div>Last Name:</div><input data-bind="value: lastName"/>
        </div>
        <div class="field">
            <div>Full Name:</div><span data-bind="text: fullName"/>
        </div>
         
        <button data-bind="click: reset">Reset</button>
    </div>

    Here is the ViewModel:
    var person = kendo.observable({
        firstName: "John",
        lastName: "DeVight",
        fullName: function() {
            return this.get("firstName") + " " + this.get("lastName");
        },
         
        reset: function() {
            this.set("firstName", "John");
            this.set("lastName", "DeVight");
        }
    }).bind("set", function(e) {
        if (e.field == "firstName" && !e.value) {
            e.preventDefault();
        }
    });
     
    kendo.bind($('#personFields'), person);

    When I change firstName to an empty value, the input field remains empty.

    I tried changing the handler for the set event to this:
    function(e) {
        if (e.field == "firstName" && !e.value) {
            var field = e.field;
            var currVal = this.get(e.field);
               this.set(field, currVal);
            e.preventDefault();
        }
    }

    But the input field still does not get reset to the "current" value.  How do I do this?

    Regards,

    John DeVight
  2. John DeVight
    John DeVight avatar
    209 posts
    Member since:
    Jan 2010

    Posted 24 Oct 2012 Link to this post

    Nevermind.  Figured out that all I had to do was take out the e.preventDefault() from the set event handler and call the set method within a setTimeout.

    function(e) {
        if (e.value.length === 0) {
            var that = this;
            var field = e.field;
            var currVal = this.get(e.field);
            setTimeout(function() {
                that.set(field, currVal);
            });
        }
    }
  3. Kendo UI is VS 2017 Ready
Back to Top