Asqan
Asqan

Reputation: 4489

Put without fetch in Backbone

i want to update a record:

www.mywebsite.com/REST/mytable/16

But; for mytable, i have to give two mandatory parameters:

www.mywebsite.com/REST/mytable?param1=this&param2=that

And if i want to take the model from this collection using the following, the record can't be found:

www.mywebsite.com/REST/mytable?param1=this&param2=that/16

This is realized by the following code:

var Model = Backbone.Model.extend({
    idAttribute : "ID"
});
var Col = Backbone.Collection.extend({
    model : Model,
    url : $scope.base + $scope.selected.table.entity.Name + "?param1=1&param2=2"
});
connector.fetch().then(function () {
                var record = connector.get(toBeChangedRecordId);

                record.set(props); //attributes as json 

                .save({
                        success : $scope.putCallback,
                        error : $scope.putCallback
                    });
}

It doesn't work because in the url above, no record is found. Instead of this, i need another way, so i can just give my ID to change the record (thus www.mywebsite.com/REST/mytable/16 + JSON object. How is that possible?

Upvotes: 1

Views: 45

Answers (1)

Benjamin Craig Adams
Benjamin Craig Adams

Reputation: 81

When you are doing a dynamic URL like this you can wrap the url method in a function like so

Backbone.Model.extend({
idAttribute : "ID",
url: function() {
    var idStr = ''
    if (this.isNew()) {
        idStr = '/' + this.get('id')
    }
    return 'http://www.mywebsite.com/REST/mytable' + idStr + '?param1=' + this.get('param1') + '&param2=' + this.get('param2');
}
});

Also, you declared your url was semantically declared wrong. You have the query string in the wrong place.

Upvotes: 1

Related Questions