简体   繁体   中英

Knockout JS refactoring

I am new to knockoutjs and I am not a JS guru either. I am banging my head on wall with this code and I need someone to help me refactor and make it DRY.

HTML Razor ASP.NET MVC

  @Html.TextBoxFor(m => m.Zip, new { @maxlength = "10", @class = "form-control",@data_bind = "value: zip, event:{ keyup: $root.getCity, keydown: $root.inputnumeric}" })

ViewModel(options) {}
    self.inputnumeric= function (data, event) {

            var key = event.keyCode;
            if (!((key == 8) || (key == 46) || (key >= 35 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105))) {
                return false;
            }
            return true;
        }

        self.getCity = function (data, event) {
            var target = event.target;
            var value = target.value;
            var data = {
                zipCode: value
            }
            if (value.length < 4) {
                $(target).removeClass('valid').addClass('error');
            } else if (value.length > 4) {
                $(target).addClass('error').removeClass('valid');
            } else if ((value.length == 4)) {

                $.getJSON(self.options.cityapiurl, data, function (result) {

                    if (result.success) {
                        self.city(result.cityName);


                        $('#City').addClass('valid').removeClass('error');
                        $(target).addClass('valid').removeClass('error');

                    } else {
                        $(target).addClass('error').removeClass('valid');
                        $('#City').addClass('error').removeClass('valid');

                    }

                })
                  .error(function () { alert("error hapens"); });

            }
        };

Now i have this on a viewmodel.js.

But I also have almost the same code on 140 other js files.

How can I make something shared between these files.

So that I have a base kllas with seft.city and self.inputnumeric so no need to copy paste the code on 140 files

You can create a GlobalModule function , a separate Js file and put in all the function in there.

Then first reference GlobalModule File and Start using it Like

GlobalModule.getCity();

Another thing that i would like to point , if you are using Knockout then you should consider using Jquery as little as possible.

As per Code snippet above , You could have used "attr" binding to change the Css as per the need.

This would make Code more clean and help improve maintenance as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM