Initialize Knockout observable from element attribute value

前端 未结 2 571
不思量自难忘°
不思量自难忘° 2021-02-05 14:30

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

2条回答
  •  情话喂你
    2021-02-05 15:06

    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...

提交回复
热议问题