简体   繁体   English

kickout.js-数据绑定属性默认值

[英]knockout.js - data-bind attr default values

I have a simple html element with an attr binding: 我有一个带有attr绑定的简单html元素:

<img src="defaultImage.png" alt="default" data-bind="attr: {src: imgUrl, alt: imgAlt}" />

What I'd like to do is have a custom extender to take the default value for src and alt and automatically initialize them into the Knockout observables. 我想做的是有一个自定义扩展器,以使用srcalt的默认值,并将它们自动初始化为Knockout可观察对象。

There are plenty of examples for doing this for a value or text binding but none for arbitrary attr bindings. 对于值或文本绑定,有很多示例可以执行此操作,但对于任意attr绑定,没有很多示例。

Is this possible? 这可能吗?

这很脏,但是如果您没有很多地方应该写它,这会有所帮助:

<img src="defaultImage.png" alt="default" data-bind="attr: { src: imgUrl() || 'defaultUrl', alt: imgAlt() || 'defaultAlt' }" />

I had the same requirement - thought this example is just only for the img tag attribute, it could be easily extended for all attributes: 我有相同的要求-认为此示例仅适用于img标签属性,可以轻松扩展所有属性:

ko.bindingHandlers.src = {
    update: function (element, valueAccessor) {
        ko.bindingHandlers.attr.update(element, function () {
            return {src: valueAccessor()};
        });
    }
};

Usage: 用法:

<img data-bind="src: imgUrl" />

The custom binding above will follow the classic way, first you will initialize the observable, then the image src attribute is updated - this means, the img src will take also the default initialization value of the knockout observable. 上面的自定义绑定将遵循经典方法,首先将初始化可观察对象,然后更新图像src属性-这意味着img src还将采用可剔除可观察对象的默认初始化值。

If you need the reverse way, you can use the custom binding init callback: 如果需要相反的方法,则可以使用自定义绑定init回调:

ko.bindingHandlers.src = {
  init: function(element, valueAccessor) {
    var value = valueAccessor();
    value(element.src);
  },
  update: function(element, valueAccessor) {
    ko.bindingHandlers.attr.update(element, function() {
      return {
        src: valueAccessor()
      };
    });
  }
};

The usage in markup is the same, but the effect at initialization is inverted. 标记中的用法相同,但是初始化时的效果相反。

Here is a Plunker: https://plnkr.co/edit/CwI6KGirOkb3XpgS0Dj8?p=preview 这是一个柱塞: https ://plnkr.co/edit/CwI6KGirOkb3XpgS0Dj8 ? p = preview

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

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