简体   繁体   English

淘汰赛中Attr绑定的问题

[英]Issue with Attr binding in knockout

I am using knockout attr binding for data- attributes, like : 我对数据属性使用敲除属性绑定,例如:

 <div data-bind="attr : { 'data-fire': Fire, 'data-age': Age }">
 </div>

Now what i want is that if any observable varibale ie Fire and Age is null or empty than i do not want to add an empty attribute name. 现在我想要的是,如果有任何可观察到的变量,即Fire and Age为null或为空,那么我不想添加空属性名称。 So after applying binding if suppose Age is empty than i do not want my markup to be : 因此,如果假设Age为空,那么在应用绑定之后,我不希望我的标记是:

 <div data-bind="attr : { 'data-fire': Fire, 'data-age': Age }"  data-age data-fire="Yes">
 </div>

Instead i want to remove data-age and want this clean markup : 相反,我想删除数据时代并想要这个干净的标记:

 <div data-bind="attr : { 'data-fire': Fire, 'data-age': Age }" data-fire="Yes">
 </div>

Is there any way to achieve this in knockout.js? 有什么方法可以在kickout.js中实现?

You can control this yourself using custom binding : 您可以使用自定义绑定自己控制此操作:

<div data-bind="addAttributes : { 'data-fire': Fire, 'data-age': Age }"></div>

Then have a handler: 然后有一个处理程序:

ko.bindingHandlers.yourBindingName = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        // This will be called when the binding is first applied to an element
        // Set up any initial state, event handlers, etc. here
    },
    update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        // This will be called once when the binding is first applied to an element,
        // and again whenever the associated observable changes value.
        // Update the DOM element based on the supplied values here.
    }
};

In these methods, you can check the values and add the attributes in manually (using jQuery, for example) only if the values aren't blank. 在这些方法中,仅当值不为空时,才可以检查值并手动添加属性(例如,使用jQuery)。

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

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