Set tag attribute based on variable value with kendo binding

落花浮王杯 提交于 2019-12-24 14:04:27

问题


  1. I create a variable list of input elements which are bound to a kendo MVVM.
  2. I have a kendo validation running over all my input elements (this is standard functionality), checking if the input is empty.
  3. The objects in my MVVM have an attribute IsMandatory, like this:

    { Name: "test", ID: 12, ... , IsMandatory: false }

  4. The validation must not try to validate elements with an IsMandatory value of false. How can I achieve this?

I know I can bind attributes to MVVM values like this:

<input data-bind="attr: { name: Name }" />

Which results in an actual output like this for the object above:

<input name="test" />

However, the required attribute used for the standard required validation is value-less, like this.

<input name="test" required />

So basically I need to create elements with a required attribute if the IsMandatory attribute in my MVVM object is set to true, and without the required attribute if it is set to false.

{ Name: "test1", ID: 1, ... , IsMandatory: true }
{ Name: "test2", ID: 2, ... , IsMandatory: false }
{ Name: "test3", ID: 3, ... , IsMandatory: true }

<input name="test1" required />
<input name="test2" />
<input name="test3" required />

Is there an elegant solution to this problem? Other than putting an if-else around the creation of each element. Or is there a different solution of excluding/including elements in my validation?

One option I could imagine would be to create a custom required validation, checking if the IsMandatory attribute for the input is set to true and only then validate the element. However, I could not find any possibility to get my hands on the MVVM object of the current element.

...
validation: {
    required: function (input) {
        var observable = // Get the kendo observable from input here !!!!!
        if (observable.IsMandatory) {
            return input.val() != "";
        }
        return true;
    }
},
...

回答1:


This can be implemented as a custom binding:

kendo.data.binders.required = kendo.data.Binder.extend({
  refresh: function() {
    var required = this.bindings.required.get();
    if (required) {
      this.element.setAttribute("required", "required");
    } else {
      this.element.removeAttribute("required");
    }
  }
});

Here is a live demo: http://jsbin.com/atozib/1/edit



来源:https://stackoverflow.com/questions/15945755/set-tag-attribute-based-on-variable-value-with-kendo-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!