Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .data() does not update HTML5 data attributes

I am trying to add a "data-bind" attribute to a div using jQuery as follows:

var messageViewModel = {
    data: ko.observable({   
        message: response.message, 
        sendDateFmted: response.sendDateFmted, 
        messageId: response.messageId
    })
     };

$("<div>",{
    class:"messageToAndFromOtherMember"
}).data("bind", "template: { name: 'message-template', data: data }").appendTo("#messagesToAndFromOtherMember");

ko.applyBindings(messageViewModel);

"data-bind" is required by KnockoutJs. However all I get is this empty div:

<div class="messageToAndFromOtherMember"></div>

Notice there is no such attribute as data-bind and therefore the div remains empty...

like image 309
balteo Avatar asked Dec 26 '22 13:12

balteo


1 Answers

jQuery's .data() stores the values in-memory and uses data-* attributes for initialization. You may want to stick by setting it at element creation.

$("<div/>", {
  class: "messageToAndFromOtherMember",
  "data-bind": "template: { name: 'message-template', data: data }"
}).appendTo("#messageToAndFromOtherMember");
like image 181
Alexander Avatar answered Jan 11 '23 20:01

Alexander