0

我正在使用单击应用程序与淘汰赛。 对于这个非常奇怪的问题,我一直在撞墙。 IE浏览器奇怪地决定不对我的可观察数组排序,而Chrome和Firefox按预期工作。Knockout-IE不排序可观察阵列(Chrome和Firefox)

下面的代码:该TR点击事件调用排序功能,但IE浏览器根本不对它进行排序

var lastResponseSort = ''; 

var sortResponses = function (data, event) { 
var sortField = $(event.target).attr("data-arg"); 

    if (sortField !== undefined) { 
    var descending = lastResponseSort != ""; 
    lastResponseSort == "" ? lastResponseSort = sortField : lastResponseSort = ""; 

    // Sort Array here 
    arrResponses.sort(function (x, y) { 
     if (descending) { 
     return x[sortField] > y[sortField] ? -1 : 1; 
     } else { 
     return x[sortField] < y[sortField] ? -1 : 1; 
     } 
    }); 
    } 

HTML:

<table id="crisis-info"> 
    <thead> 
    <tr data-bind="click: sortResponses"> 
     <th data-arg="eventName">Response name</th> 
     <th data-arg="eventRelatesCrisisTypes()[0].crisisType().name">Crisis Type</th> 
     <th data-arg="numberOfPeopleAffected">Affected</th> 
     <th data-arg="country().name">Country &amp; Region</th> 
    </tr> 
    </thead> 
    <tbody data-bind="visible: arrResponses().length > 0, foreach: arrResponses"> 
     <tr> 
     <td><span data-bind="text: eventName(), attr: { title:eventName() }"></span> 
     </td> 
     <td><span data-bind="text: eventRelatesCrisisTypes()[0].crisisType().name(),attr: { title: eventRelatesCrisisTypes()[0].crisisType().name() }"></span> 
     </td> 
     <td align="center"><span data-bind="text: numberOfPeopleAffected()"></span> 
     </td> 
     <td><span data-bind="text: country().name() + ', ' + country().region().name()"></span></td> 
     </tr> 
     </tbody> 
    </table> 

这是更迷人的问题的一部分是在应用调试器并且执行sort函数时,IE甚至不会对数组进行排序,更不用说更新我认为是问题的UI,也不会抛出任何错误。如果有人遇到此问题或知道解决方法,请分享。 谢谢

+0

'x [sortField]'不是你想要的。你需要做一些像'eval('x。'+ sortField)'。 –

+0

仍然是一样的...与铬合作,但不在IE:( – Sarcastic

+1

由于属性是可观察到的,你也需要解开它们:'eval('x。'+ sortField)()'当我看到它时,你的代码无法在任何浏览器中工作 –

回答

1

由于您试图动态访问对象的属性和/或子属性,因此您需要使用eval而不是动态属性访问。因此x[sortField]将需要是eval('x.' + sortField)

此外,由于属性是可观察的,您还需要添加尾随括号:eval('x.' + sortField)()

这是你更新排序功能(与其他一些优化):

arrResponses.sort(function (x, y) { 
    var xLess = eval('x.' + sortField + '() < y.' + sortField + '()'); 
    if (descending) { 
     return xLess ? 1 : -1; 
    } else { 
     return xLess ? -1 : 1; 
    } 
}); 

另外的解决办法,我建议你更强烈,是使用计算机可观察在你的对象封装所显示的数据。因此,你的Response对象将包含以下内容:

this.crisisType = ko.computed(function() { 
    return this.eventRelatesCrisisTypes()[0].crisisType().name();  
}, this); 

this.countryRegion = ko.computed(function() { 
    return this.country().name() + ', ' + this.country().region().name(); 
}, this); 

现在你可以结合这些观测计算在您看来,在你的排序功能使用它们,而不必使用eval