jQuery .data() does not update HTML5 data attributes

后端 未结 2 1602
遇见更好的自我
遇见更好的自我 2021-01-20 01:18

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

var messageViewModel = {
    data: ko.observable({   
                


        
2条回答
  •  花落未央
    2021-01-20 01:50

    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);
        };
    };
    

提交回复
热议问题