从元素属性值初始化Knockout observable [英] Initialize Knockout observable from element attribute value

查看:99
本文介绍了从元素属性值初始化Knockout observable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个元素拥有一个属性,其值绑定到一个可以观察到的敲除:

I have an element that possesses an attribute whose value is bound to a knockout observable:

< text transform ='matrix(1 0 0 1 1 1)'data-bind ='attr:{transform:textTransform}'>< / text>

元素加载我喜欢observable包含在dom元素上定义的值,但是它反而加载为undefined并且属性从dom元素中全部删除:

When the element loads I'd like the observable to contain the value defined on the dom element, however it instead loads as undefined and the attribute is removed from the dom element alltogether:

< text data-bind ='attr:{transform:textTransform}'>< / text>

是否可以从dom元素属性初始化knockout observable的值并同时保持dom元素属性的值?

Is it possible to initialize the value of a knockout observable from a dom element attribute and persist the value of the dom element attribute as well?

UPDATE: http://jsfiddle.net/5Z2SC/10/

推荐答案

另一种选择是使用自定义绑定,并收集in中元素的当前值它的功能。在我看来,这是更可重用的。

Another option would be to use a custom binding, and collect the current value of the element in the init function. This is much more reusable, in my opinion.

ko.bindingHandlers.transform = {
    init: function(element, valueAccessor) {
        valueAccessor()(element.getAttribute('transform'));
    },
    update: function(element, valueAccessor) {
        var value = valueAccessor();
        element.setAttribute('transform', ko.utils.unwrapObservable(value))
    }
};

当然,你的工作会更复杂,因为你必须这个转换属性的东西。该逻辑可能希望进入更新部分。

Of course, yours will be more complicated, since you must be doing something with this transform property. That logic will probably want to go in the update section.

这篇关于从元素属性值初始化Knockout observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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