This is a migrated thread and some comments may be shown as answers.

Validating and resetting a property in the View

1 Answer 193 Views
MVVM
This is a migrated thread and some comments may be shown as answers.
John DeVight
Top achievements
Rank 1
John DeVight asked on 24 Oct 2012, 06:40 PM
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

1 Answer, 1 is accepted

Sort by
0
John DeVight
Top achievements
Rank 1
answered on 24 Oct 2012, 06:56 PM
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);
        });
    }
}
Tags
MVVM
Asked by
John DeVight
Top achievements
Rank 1
Answers by
John DeVight
Top achievements
Rank 1
Share this question
or