Initialize Knockout observable from element attribute value

随声附和 提交于 2019-12-03 03:06:35

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.

the data-bind attributes are not parsed until you call ko.applyBindings(). So if you need to get attribute data off of your elements you can do it like this.

function MyModel(){
    this.textTransform = ko.observable($('#myElement').attr('transform'));
}

ko.applyBindings(new MyModel());

basically, you are grabbing the value of the attribute and setting it as the initial value of the observable. the data-bind attributes are meant to be a template, so initial or default values should be specified in your ViewModel.

the other option is to write a custom binder, that can store a default if the observable returns null...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!