Validate javascript inside attributes
Asked Answered
C

1

0

I am using Knockout a lot and often times I have to write scripts inside the data-bind attributes. Is there any validation tools that I can use on these markup files to validate the javascript inside data-bind attributes? Would be nice if there is a grunt plugin.

Color answered 27/8, 2015 at 16:26 Comment(4)
Tools to validate what? This is very vague.Criner
check modelview.js a fast MVVM framework (inspired among others by knockout) with a versatile and extendable typecasting/validation system (ps author)Announcer
the above comment, is if i understand correctly that validation is needed for MVVM, if onthe other hand validation is needed for grunt (other type of validation meant), ignore previous commentAnnouncer
you shouldn't have to write/define your functions within the data-binds, just call them from there. The functions should be done within your viewmodel.Kershaw
C
3

There probably isn't (a prominent) one, because it's not common to have a lot of complex logic inside your view. With MVVM-like approaches it works best if you keep the View rather plain, and write out logic in your ViewModel where you can unit test it.

So do not do this:

var ViewModel = function() {
  var self = this;
  
  self.isCurrent = ko.observable(false);
  self.item = ko.observable({ id: 42 });
}

ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<!-- Don't do this! -->
<div data-bind="visible: !isCurrent() && !!item()">
  Showing something!
</div>

Instead, do this:

var ViewModel = function() {
  var self = this;
  
  self.isCurrent = ko.observable(false);
  self.item = ko.observable({ id: 42 });
  
  self.shouldShowItem = ko.computed(function() {
    return !self.isCurrent() && !!self.item();
  });
}

ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<!-- Don't do this! -->
<div data-bind="visible: shouldShowItem">
  Showing something!
</div>

Because that would allow you to unit test the shouldShowItem logic, e.g. with QUnit:

QUnit.test("shouldShowItem is false if not isCurrent and item not set", function(assert) {
    var vm = new ViewModel();
    vm.isCurrent(false);
    vm.item(null);
    assert.strictEqual(vm.shouldShowItem(), false);
});

Bottom line, if you find yourself writing out lots of logic inside your view, you probably need to move some of it to your view models and make it testable.

Chaco answered 27/8, 2015 at 17:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.