从knockoutJS中的observableArray中删除Self

Removing Self From observableArray in knockoutJS

本文关键字:删除 Self observableArray knockoutJS 中的      更新时间:2023-09-26

我正在使用knockoutjs创建分区的树视图。每个节点旁边都有三个按钮:1)新建子节点(应用于它旁边的节点)删除(这将删除它旁边的结点)和3)复制,它复制节点及其所有子节点,并在父节点下创建一个新节点。

我按下了"新建"按钮,现在我正在处理"删除"按钮。我似乎无法让它工作,它没有做任何有用的事情,只是刷新了整个页面。这是代码:

视图:

<h2>Skill & Weight Divisions</h2>
        <span data-bind="text: tournamentname"></span><button data-bind="click: addDivision"><img src="new.png"/></button>
        <ul data-bind="template: { name: 'divisionTemplate', foreach: divisions }"></ul>

模板:

<script id="divisionTemplate" type="text/html">
   <li data-bind="style: {'background-color':color}">
       <input data-bind="value: name"/><button data-bind="click: addDivision"><img src="new.png"/></button><button data-bind="click: $parent.removeDivision"><img src="remove.png"/></button><button data-bind="click: $parent.copyDivision"><img src="copy.png"/></button>
       <ul data-bind="template: { 'if': children, name: 'divisionTemplate', foreach: children }"></ul>
    </li>       
</script>

视图模型和适当的辅助功能:

function division(id, name, filter, children) {
        this.id = ko.observable(id);
        this.name = ko.observable(name);
        this.filter = ko.observable(filter)
        if(children){
            this.children = ko.observableArray(children);   
        }else{
            this.children = ko.observableArray();   
        }
        this.addDivision = function(){
            this.children.push(new division("", "", ""));   
        }
        this.removeDivision = function(division){
            this.children.remove(division);
        }
        this.copyDivision = function(division){
            this.children.push(division);   
        }
        this.color = randColor();
    };
    function tournamentViewModel(){
        var self= this;
        self.tournamentname = ko.observable('NO NAME YET');
        self.districts = ko.observableArray([new district('Provo',1),new district('Salt Lake City',2),new district('St. George',3)]);
        self.district = ko.observable(self.districts()[0]);
        self.regions = ko.observableArray([new region('Utah',1),new region('Idaho',2)]);
        self.region = ko.observable(self.regions()[0]);
        self.location = ko.observable('WHEREVER YOU WANT');
        self.eventdate = ko.observable('');
        self.startTime = ko.observable('');
        self.image = ko.observable();
        self.flyer = ko.computed(function(){
            var flyerHTML = '<span style="text-align:center;padding:10px;"><h1>'+self.tournamentname()+'</h1><img src="'+self.image()+'"/><br/>';
            flyerHTML += 'District: ' + self.district().districtName + ' Region: ' + self.region().regionName+'<br><br>';
            flyerHTML += '<h2>WHEN: '+self.eventdate()+' '+self.startTime()+'</h2>';
            flyerHTML += '<h2>WHERE: '+self.location()+'</h2>';
            flyerHTML += '<img src="http://maps.googleapis.com/maps/api/staticmap?center='+encodeURI(self.location())+'&zoom=12&size=200x200&markers=color:blue%7Clabel:S%7C'+encodeURI(self.location())+'&maptype=roadmap&sensor=false"/>';
            return flyerHTML;
        }, self);
        self.clearImage = function(){
            self.image(''); 
        }
        self.tournamentID = ko.computed(function(){return 't_'+self.district()+'_'+self.region()+'_'+self.eventdate()}, self);
        self.pricingStructures = ko.observableArray([new pricingStructure(3,2.99), new pricingStructure(1,1.99)]);
        self.removePricingStructure = function(pricingStructure){
            self.pricingStructures.remove(pricingStructure); 
        }
        self.addPricingStructure = function(){
            self.pricingStructures.push(new pricingStructure("", ""));  
        }
        self.promoCodes = ko.observableArray();
        self.promoTypes = ['%','$'];
        self.removePromoCode = function(promoCode){
            self.promoCodes.remove(promoCode); 
        }
        self.addPromoCode = function(){
            self.promoCodes.push(new promoCode("", ""));    
        }
        self.divisions = ko.observableArray([new division(1, "Men","",[new division(2,"Gi"), new division(3,"No-Gi")])]);
        self.addDivision = function(){
            self.divisions.push(new division("", "", ""));  
        }
    }
    ko.applyBindings(new tournamentViewModel());

在这一切中,我的主要问题是:有没有一种方法可以访问对象的父数组,以便从数组中删除该对象?提前感谢您的帮助!

编辑:这是一个jsFiddle:http://jsfiddle.net/eqY7Z/然而,它似乎在那里根本不起作用。如果你们不能让它继续下去,我会把它托管在我的网站上的链接包括在内,这样你们就可以好好看看了。

我接受了你的想法,制作了一把工作小提琴,它的行为与你描述的完全一样。对不起,我不想试图解决你的问题。它有很多与你的问题没有直接关系的东西,这个解决方案足够通用,其他人应该能够使用它。如果你需要帮助调整它,请告诉我。

需要注意的一点是克隆功能。您的复制函数不深入,会导致多个节点指向同一个对象。如果要更新节点值,它将传播到其克隆。Knockout提供了一个方便的深度复制+用ko.toJS打开可观测值。超级有用。

JS:

var Node = function(name, children) {
    var self = this;
    self.name = ko.observable(name || 'NewNode');
    self.children = ko.observableArray(
    ko.utils.arrayMap(children || [], function(i) {
        return new Node(i.name, i.children);
    }));
    self.newChild = function() {
        self.children.push(new Node());
    };
    self.removeNode = function(node) {
        self.children.remove(node);
    };
    self.copyNode = function(node) {
        var cloneNode = ko.toJS(node);
        self.children.push(new Node(cloneNode.name, cloneNode.children));
    };
};
//Example data removed for brevity, see fiddle
ko.applyBindings(new Node(data.name, data.children));​

HTML:

<button data-bind="click: newChild">NewNode</button>
<ul data-bind="template: { name: 'treeTemplate', foreach: children}">
</ul>
<script id="treeTemplate" type="text/html">
    <li>
        <input data-bind="value: name" />
        <button data-bind="click: newChild">New Child</button>
        <button data-bind="click: $parent.removeNode">Remove Node</button>
        <button data-bind="click: $parent.copyNode">Copy Node</button>
        <ul data-bind="template: { name: 'treeTemplate', foreach: children}"></ul>
    </li>
</script>
​

我能够在以下jsFiddle中创建代码的工作版本:http://jsfiddle.net/3eQNf/.它似乎归结为两个主要问题:

  1. 您在除法类中使用"this"关键字时遇到了上下文问题。添加自变量解决了这个问题。

  2. 您需要添加一个根级别的除法并绑定到它的子级。这使得所有递归都能按预期工作。这样做还消除了对锦标赛ViewModel 中addDivision方法的需求

此外,仅供参考,我需要为您的地区、地区和pricingStructure类添加存根,因为这些没有包含在您上面的示例代码中。希望这能有所帮助。