我可以创建一个在knockout.js中使用其他绑定的自定义绑定 [英] Can I create a custom binding that uses other bindings in knockout.js

查看:83
本文介绍了我可以创建一个在knockout.js中使用其他绑定的自定义绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义的翻译绑定:

I have a custom binding for translations:

ko.bindingHandlers.lang = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        this.lang = [
            'text1':'text1 translated'
            ,'text2':'text2 translated'
        ];
    },
    update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var keyword = valueAccessor();
        var translatedString = this.lang[keyword];
        $(element).text(translatedString );
    }
};

我用的是这样的:

<span data-bind="lang:'text1'"></span>

但是,我还有一个用于创建表格行格式的绑定:

However, I also have a binding for creating a table row formating:

ko.bindingHandlers.tableRow = {
    update : function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        $(element).html("<td>" + valueAccessor()[0] + "</td><td>" + valueAccessor()[1] + "</td>");
    }
}

我用的是这样的:

<tr data-bind="tableRow:['text1','text2']"></tr>



问题:



现在我想要组合这些绑定,所以我可以这样调用我的tableRow绑定:

To the question:

Now I would like to combine these bindings so I could call my tableRow binding like this:

<tr data-bind="tableRow:[lang:'text1','text2']"></tr>

上面的代码只是例如,实际上这些绑定还有更多。

The code above is ofcourse only for example, in reality there's more going on in these bindings.

我已多次阅读文档并花了很长时间寻找解决方案但找不到任何东西。也许是因为无法做到这一点?

I have read through the documentation multiple times and spent a long time searching for a solution but couldn't find anything. Maybe because this can't be done?

推荐答案

您需要做的就是将值从一个bindingHandler中继或修改为其他你想激活的。

All you need to do is relay or modify the values from one bindingHandler to the other ones you want to activate.

因此,在你的tablerow处理程序中,调用init和update(在各自的函数中):

So, in your tablerow handler, call init and update (in their respective functions):

ko.bindingHandlers.lang.init(element, valueAccessor, allBindingsAccessor, viewModel)

当然需要修改参数。您可能会从数组中获取其中一个值,并将其作为第二个参数传递给init和update。

Modify the parameters as needed of course. It's likely you'll grab one of the values from your array and pass it as the second parameter to init and update.

这也是激活其他标准内置绑定的好方法。

This is a great way to activate other standard built in bindings as well.

更新:添加来自 @Joche 的评论这更具可读性:

Update: Adding the comment from @Joche just to make this more readable:

var value = valueAccessor(); 
var newValueAccessor = function() {
    return translatedString; }; 
ko.bindingHandlers.lang.init(element, newValueAccessor,
       allBindingsAccessor, viewModel);

这篇关于我可以创建一个在knockout.js中使用其他绑定的自定义绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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