2014-07-07 80 views
0

我建立一個應用程序,我需要將數據發佈到服務器。在這一點上,我一直在使用模型的唯一方法是在應用程序中接收/獲取數據。現在我想發佈。我想知道如何以好的方式做到這一點。我想通過一個叫做「後模型」的模型或其他東西?Backbone.js模型帖子

我基本上只想調用一個API並傳遞一些參數。喜歡這種:

/api/?action=answerQuestion&question_id=*my id here* 

我該怎麼做呢?

回答

0

你需要做的是在你的模型中創建一個新的功能,並從該功能「手動」執行請求。事情是這樣的:

MyModel = Backbone.Model.extend({ 
    initialize: function(){ 
    ... 
    }, 
    post_to_api: function(){ 
    var data = { 
     "question_id": this.id, 
     "action": "answerQuestion" 
    }; 
    $.post("http://api.com/", data, function(response) { 
     // post success callback 
    }); 
    }, 
}); 

然後使用這個,你會實例MyModel並調用post_to_api功能:

var model = new MyModel({ "id": 42 }); 
model.post_to_api();