未捕获的TypeError:无法读取未定义的属性“长度”

时间:2011-05-15 22:40:44

标签: javascript jquery knockout.js

我正在努力建立一个按联系人姓氏的第一个字母分组的联系人列表。

在成功的ajax请求之后,联系人被推送到addContact:

Ajax成功:

    ko.utils.arrayForEach(dataJS.contactList, function(c) {
        contactsModel.addContact(c);
    });

contactsModel.addContact:

//add a contact in the right spot under the right letter
contactsModel.addContact = function(newContact) {
    //grab first character
    var firstLetter = (newContact.lname || "").charAt(0).toUpperCase();
    //if it is a number use #
    if (!isNaN(firstLetter)) {
        firstLetter = "#";
    }

    //do we already have entries for this letter
    if (!this.letterIndex[firstLetter]) {
    //new object to track this letter's contacts
        var letterContacts = {
            letter: firstLetter,
            contacts: ko.observableArray([])
        };

        this.letterIndex[firstLetter] = letterContacts; //easy access to it

        //put the numbers at the end
        if (firstLetter === "#") {
            this.contactsByLetter.push(letterContacts);
        } else {
            //add the letter in the right spot 
            for (var i = 0, lettersLength = this.contactsByLetter().length; i < lettersLength; i++) {
                var letter = this.contactsByLetter()[i].letter;

                if (letter === "#" || firstLetter < letter) {
                     break;  
                }
            }  
            this.contactsByLetter.splice(i, 0, letterContacts);
        }
    }

    var contacts = this.letterIndex[firstLetter].contacts;

    //now we have a letter to add our contact to, but need to add it in the right spot
    var newContactName = newContact.lname + " " + newContact.fname;
    for (var j = 0, contactsLength = contacts().length; j < contactsLength; j++) {
        var contactName = contacts()[j].lName + " " + contacts()[j].fName;

        if (newContactName < contactName) {
           break;  
        }
    }

    //add the contact at the right index
    contacts.splice(j, 0, newContact);

}.bind(contactsModel);

来自服务器的联系人json对象如下所示:

{
        "total_pages": 10,
        "page": page,
        "contactList": [{
            "photo": "http://homepage.mac.com/millhouse/Family%20Tree/images/PersonListIcon.png",
            "lname": "Bond",
            "id": 241,
            "fname": "James",
            "email": "xxx@yahoo.com"},

虽然这在jsfiddle中有效,但是当我在本地尝试时,我在第一次推送addContact时遇到以下错误:

Uncaught TypeError: Cannot read property 'length' of undefined
jQuery.jQuery.extend._Deferred.deferred.resolveWithjquery-1.5.1.js:869
donejquery-1.5.1.js:6591
jQuery.ajaxTransport.send.callbackjquery-1.5.1.js:7382

想法?感谢

2 个答案:

答案 0 :(得分:1)

您的语法在for循环和其他地方看起来是错误的,即()用于调用函数。尝试在contactsByLetter()contacts()contactsByLettercontacts的任何地方进行更改。

答案 1 :(得分:0)

确保将bindings语句包装在jQuery ready ...

$(function(){
    ko.applyBindings(contactsModel, document.getElementById("view-panel-contacts"));
});

使用你在小提琴中提供的代码对我有用。

http://pastebin.com/YYfBB0ES