vicenrele
vicenrele

Reputation: 971

How to execute a Model's function from a View in Backbone.js when a plugin event is triggered?

I have the next code:

var Contents = Backbone.View.extend({       
    events: {
            "click #addAll": "addContent"
    },
    initialize: function() {
        _.bindAll(this); 
        this.model = new ContentCollection();
        this.model.on("add", this.contentAdded);
    },                  
    addContent: function(event) {
        this.model.add({ modelName: "all"});
        //Plugin event
        $('select').switchify().data('switch').bind('switch:slide', function(e,type){       
            //Do something

        });     
    },          
    contentAdded: function(content) {
        if (content.view == null) {
            var template_name;              
            switch(content.get("modelName")){   
                case 'all': template_name = 'home'; break;  
            }                                       
            content.view = new ContentView({
                              model: content, template: //template
                     });
            $(".box").empty(); 
            content.functionModel();    
            //render template                                               
            }       
        },              
}); 

When a button (#addAll) is clicked, a model is added to the Collection, then view is made, functionModel is called and template is rendered. I want to execute funtionModel() when plugin event is done, but is neccesary content of the particular model maked to call the function. And the plugin doesn't work in contentAdded.

Upvotes: 0

Views: 123

Answers (1)

jevakallio
jevakallio

Reputation: 35890

I'm not 100% sure I've understood your problem correctly, but I gather you need to get a reference to the Content model in the addContent method. I hope this is correct.

Instead of allowing the collection.add method to create the model for you like you do now:

this.model.add({ modelName: "all"});

initialize the model separately:

var content = new ContentModel( modelName: "all" });
this.model.add(content);

When you have a local variable (content), it is also accessible in the scope of the plugin event handler callback. The following should work:

addContent: function(event) {
    var content = new ContentModel( modelName: "all" });
    this.model.add(content);
    $('select').switchify().data('switch').bind('switch:slide', function(e,type){       
        content.functionModel();
    });     
},    

Upvotes: 2

Related Questions