簡體   English   中英

如何在觸發插件事件時從Backbone.js中的View執行Model函數?

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

我有下一個代碼:

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 )時,會向Collection添加模型,然后進行查看, functionModel並呈現模板。 我想在插件事件完成時執行funtionModel() ,但是需要調用該函數的特定模型的必要content 並且插件在contentAdded不起作用。

我不是100%確定我已正確理解您的問題,但我知道您需要在addContent方法中獲取對Content模型的引用。 我希望這是正確的。

而不是像現在這樣允許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();
    });     
},    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM