Search code examples
backbone.jstastypie

How do I check to see if data exists in a particular field of my model in backbone?


I have a model. I have notes that I add to that model. No problems there.

When I instantiate the view, I want to see if the data.objects has content in the note.

Where do I put the if statement? In the view render? And how do I test for it.

js and backbone noob here, so please forgive me missing the basics.

Lemme know and many thanks.

Any references to tutorials are welcome.

UPDATE: Here's the View for my model

var BlasterView = Backbone.View.extend({

    tagName: 'li',
    className: 'blaster',

    events: {

        'click .td-blaster a': 'done'

    },

    initialize: function() {

        _.bindAll(this, 'render');

    },

    render: function(){

        this.$el.html(ich.blasterTemplate(this.model.toJSON()));
        return this;

    },

    done: function(){

        this.model.toggle();

        this.$el.animate({
            backgroundColor:'#faeca9'
        }, 600 ).delay(600).fadeOut('fast');

        return false;

    }

});

Solution

  • render: function(){
    
        if( this.model.get('particularField') ){
           console.log('Particular Field has a value');
        }else{
           console.log('Particular Field does NOT have a value');
        }
    
        this.$el.html(ich.blasterTemplate(this.model.toJSON()));
        return this;
    
    },
    

    If you mean that also the field is an instance of an object, just do this, check that particularField is not empty and also check that the nested property is set:

    if( this.model.get('particularField') && 
    this.model.get('particularField').someChildAttr){
    

    UPDATE:

    "Backbone now supports the has property" (via: @TyroneMichael). So you can just use:

    this.model.has('particularField')