从knockoutJS中删除self from observableArray

时间:2012-07-13 04:05:58

标签: javascript arrays knockout.js ko.observablearray

我正在使用knockoutjs来创建一个分区的树视图。每个节点旁边将有三个按钮:1)新子节点(适用于它旁边的节点2)删除(这将删除它旁边的节点,以及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/然而它似乎根本没有工作。如果你们不能实现它,我会在我的网站上添加链接,以便你可以好好看看它。

2 个答案:

答案 0 :(得分:2)

我接受了你的想法并制作了一个working fiddle,其行为正如你所描述的那样。对不起,我不想尝试排除你的。它有很多与你的问题没有直接关系的东西,这个解决方案很通用,其他人应该可以使用它。如果您需要帮助进行调整,请告诉我。

需要注意的一件事是克隆功能。您的复制功能不深,会导致多个节点指向同一个对象。如果要更新节点值,它将传播到其克隆。 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>
​

答案 1 :(得分:1)

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

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

  2. 您需要添加单个根级别分区并绑定到其子级。这使得所有递归按预期工作。这样做也消除了对tournamentViewModel的addDivision方法的需要

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