Search code examples
arraysbackbone.js

How do I access this array in backbone?


I’m new to Backbone, but I’ve successfully been able to define an array like this on one of my models:

buildMyArray: function() {
    var self = this;

    var myArray = {};

    window.myLibrary.getStuff('myParameter', function(myStuff) {
        for (var myKey in myStuff) {
            if (myStuff.hasOwnProperty(myKey)) {
                var myValue = myStuff[myKey];
                myArray[myKey] = myValue;
            }
        }

        self.set({ myArray: myArray });
    });
}

However, how can I access that array from other properties? In other words, I want to do something like this:

checkArrayStuff: function(arrayKey) {
    //loop through myArray and check value for arrayKey.
    //var myArray1 = self.get(myArray);
    //var myArray2 = this.get(myArray);
    //var myArray3 = myArray;
    //var myArray4 = this.myArray;
    //var myArray5 = self.get('myArray');
    //var myArray6 = this.get('myArray');
    var myArray7 = self.myArray;

    var can = myArray7[arrayKey];
    return can;
}

I’ve tried several variations of self, this, with-and-without-quotes, with-and-without get-method, etc.


Solution

  • I guess you would have to do this

    checkArrayStuff: function(arrayKey) {
        return this.get('myArray')[arrayKey];
    }