简体   繁体   English

对象文字中的自定义敲除绑定

[英]custom knockout binding in object literal

how can i implement multiple custom knockout bindings that can be declared in an object literal? 如何实现可以在对象文字中声明的多个自定义敲除绑定?

basically instead of doing this: 基本上不是这样做:

 <input data-bind="customBinding1:observable1, customBinding2: observable2 }" />

I would like to be able to do this: 我希望能够做到这一点:

<input data-bind="customBinding0: { customBinding1: observable1, customBinding2: observable2 }" />

thanks in advance. 提前致谢。

With Knockout, bindings are specified in name/value pairs, where name is the name of the binding, and value is the value that will be retrieved within the binding using valueAccessor() . 使用Knockout,绑定以名称/值对的形式指定,其中name是绑定的名称, value是将使用valueAccessor()在绑定内检索的值。

It sounds like you may be wanting to pass multiple values in to a binding, like your kendo example shows. 听起来像您可能想将多个值传递给绑定,如您的kendo示例所示。 Although each binding can only have a single value, that value can be anything. 尽管每个绑定只能有一个值,但是该值可以是任何值。 This means you can pass in an object literal as the value, and the object can have as many properties as you want. 这意味着您可以传入对象文字作为值,并且该对象可以具有任意数量的属性。 These properties can also be of any type that you want - you'll just need to handle them correctly inside your binding. 这些属性也可以是您想要的任何类型-您只需要在绑定中正确处理它们即可。

Here's a simple example: 这是一个简单的例子:

View 视图

<div data-bind="myBinding: {setting1: viewModelProperty1, 
                            setting2, viewModelProperty2}"></div>

Binding 捆绑

ko.bindingHandlers.myBinding = {
    init: function(element, valueAccessor) {
        var options = valueAccessor() || {};

        //this gives you the value of setting1
        var setting1 = ko.utils.unwrapObservable(options.setting1);

       //if you need to do something just when `setting1` changes,
       //  add a subscription to the value like so:
       if( ko.isObservable(options.setting1) ){
           options.setting1.subscribe(function(newValue){
              //do something because the setting1 value changed
           });
       }
    }
};

You also have the option of specifying multiple bindings, each with its own value, and referencing the additional bindings and values from within the first one. 您还可以选择指定多个绑定,每个绑定都有其自己的值,并从第一个绑定中引用其他绑定和值。 Knockout's options and optionsText bindings are an example of this approach. 淘汰赛的optionsoptionsText绑定就是这种方法的一个示例。

Excellent Resource: http://www.knockmeout.net/2011/07/another-look-at-custom-bindings-for.html 优秀资源: http : //www.knockmeout.net/2011/07/another-look-at-custom-bindings-for.html

Take some time to study and experiment with the examples at the link above. 请花一些时间研究和尝试上面链接中的示例。 There's a lot of good information here that covers what you need to do. 这里有很多很好的信息,涵盖了您需要做的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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