jQuery .data() does not update HTML5 data attribut

2020-04-09 16:15发布

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

2条回答
我想做一个坏孩纸
2楼-- · 2020-04-09 16:43

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");
查看更多
我想做一个坏孩纸
3楼-- · 2020-04-09 16:43

Alexander's answer is definitely correct, in the general sense, but I couldn't help but notice that in your specific example you seem to be adding messages to your code by creating a new binding scope for each message. If this is the case, I think you are using Knockout incorrectly (if not, let me know and I will just remove this).

If you are getting new messages from a server, and just trying to display the list of them on the page, a much better structure would be to use an ObservableArray, and simply push new messages to it. The standard knockout binding will automatically add the new messages to your html, without the mess of creating a new binding scope, and a completely independent viewmodel for the new message. You can see this in action in this fiddle.

Here is the rather contrived 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);
    };
};
查看更多
登录 后发表回答