使用Kendo绑定基于变量值设置标签属性 [英] Set tag attribute based on variable value with kendo binding

查看:295
本文介绍了使用Kendo绑定基于变量值设置标签属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 我创建绑定到剑道MVVM的输入元素的可变列表.
  2. 我对所有输入元素(这是标准功能)运行一个kendo验证,检查输入是否为空.
  3. 我的MVVM中的对象具有属性IsMandatory,如下所示:

  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 }

验证不得尝试验证IsMandatory值为false的元素.我该如何实现?

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

我知道我可以像这样将属性绑定到MVVM值:

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" />

但是,用于标准所需验证的required属性是无值的,像这样.

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

<input name="test" required />

因此,基本上,如果我的MVVM对象中的IsMandatory属性设置为true,则需要创建具有必需属性的元素,而如果将其设置为false,则需要创建不具有必需属性的元素.

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 />

是否有解决此问题的简便方法?除了在每个元素的创建周围添加if-else之外.还是在验证中排除/包含元素有其他解决方案?

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?

我可以想象的一个选项是创建一个自定义的必需验证,检查输入的IsMandatory属性是否设置为true,然后才验证该元素.但是,我找不到任何机会使用当前元素的MVVM对象.

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;
    }
},
...

推荐答案

这可以实现为自定义绑定:

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");
    }
  }
});

这是一个实时演示: http://jsbin.com/atozib/1/edit

这篇关于使用Kendo绑定基于变量值设置标签属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆