如何在触发插件事件时从Backbone.js中的View执行Model函数?

时间:2013-01-12 17:13:26

标签: javascript jquery backbone.js

我有下一个代码:

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                                               
            }       
        },              
}); 

单击按钮(#addAll)时,会向集合中添加模型,然后进行查看,调用functionModel并呈现模板。 我想在插件事件完成时执行funtionModel(),但是需要调用该函数的特定模型的content。该插件在contentAdded中无效。

1 个答案:

答案 0 :(得分:2)

我不是100%确定我已正确理解您的问题,但我知道您需要在Content方法中引用addContent模型。我希望这是正确的。

而不是让collection.add方法像你现在一样为你创建模型:

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

单独初始化模型:

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

当你有一个局部变量(content)时,它也可以在插件事件处理程序回调的范围内访问。以下应该有效:

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();
    });     
},    
相关问题