JQuery.data () does not update HTML5 data attributes

I am trying to add a data binding 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 binding " is required by KnockoutJs. However, all I get is an empty div:

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

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

+4
source share
2 answers

jQuery .data() stores values ​​in memory and uses data-* attributes to initialize. You may want to stick to it by setting it when creating the element.

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

Alexander's answer is definitely correct, in a general sense, but I couldn't help but notice that in your specific example, you seem to add messages to your code, creating a new binding area for each message. If so, I think you are using Knockout incorrectly (if not, let me know and I will just delete it).

If you receive new messages from the server and just try to display their list on the page, a much better structure is to use ObservableArray and just click on it with new messages. The standard knockout binding will automatically add new messages to your html, without the mess of creating a new binding area and a completely independent presentation model for the new message. You can see it in action in this fiddle .

Here is a pretty far-fetched ViewModel:

 var ViewModel = function(data) { var self = this; self.messages = ko.observableArray(); self.newMessage = ko.observable(''); self.addMessage = function() { var message = new Message({ message: self.newMessage()}); self.newMessage(''); self.messages.push(message); }; }; 
+2
source

All Articles