Search code examples
backbone.jsunderscore.jsbackbone-views

checking an attribute of an object in an array


I need to write out a certain header in my template if an office has rental space or not. Basically I'm just going to have it right out something like this:

<div>Office Unit
    {% if (m.hasRentalSpace) { %}
        <h2>Office space available!</h2>
    {% } else { %}
        <h3>There are currently no office units for rent in this building.</h3>
    {% } %}
</div>

In the model, the rental units are an array, and I'd need to iterate through the array, and check if their status is 4(which means space available).

So I thought about doing something like this in my backbone model:

   hasRentalSpace: function() {
        this.Office.each( function(o) {
            console.log('o is: ', o.status);
        });
    },

the problem is, for each 'o', I need to access an attribute called 'status'. But if I check it by doing the test above, I get undefined everytime. But, if I write out just 'o', I can see the status attribute in the conole like this:

enter image description here

So, question is, how can I get the status of the object while iterating through the array?

Thanks!

Once I get the logic sorted out, I'll be able to use the hasRentalSpace function in my view like this:

in my view:

render: function () {
this.$el.html(this.template(hasRentalSpace: this.model.hasRentalSpace()));
    return this;
},

Solution

  • Assuming the offices are backbone models (which seems to be the case from your screen shot), instead of

    console.log('o is: ', o.status);

    You should use

    console.log('o is: ', o.get("status"));