How do I swap two items in an observableArray?

后端 未结 4 1884
轮回少年
轮回少年 2020-12-03 05:05

I have a button that moves an item one position left in an observableArray. I am doing it the following way. However, the drawback is that categories()[index] gets removed f

4条回答
  •  忘掉有多难
    2020-12-03 05:40

    I had a similar problem as I wanted jQuery drag & drop on my items. My solution became to use knockoutjs templates to bind the beforeRemove and afterAdd events to the model. The Person Class/function is also a simple knockout view model.

    In the below example I use .draggable(), but you could easily use validation. Add your own code for manipulating the observableArray and you should be good to go.

    HTML:

    ViewModel:

    var ViewModel = function () {
        var self = this;
        var at = [new Person('First', 'Person', 'first@example.com'),
                        Person('Second', 'Person', 'second@example.com')
                    ];
        self.attendees = ko.observableArray(at);
    
        self.removeAttendee = function (attendee) {
            self.attendees.remove(attendee);
        };
    
        this.showAttendee = function (elem) {
            if (elem.nodeType === 1) {
        $(elem).hide().show("slow").draggable();//Add jQuery functionality 
            }
        };
        this.hideAttendee = function (elem) {
            if (elem.nodeType === 1) {
                $(elem).hide(function () {
                    $(elem).remove();
                });
            }
        };
    };
    
    ko.applyBindings(new ViewModel());
    

提交回复
热议问题