mottalrd
mottalrd

Reputation: 4490

Backbone model and Ajax call

I am new to backbone and I am facing this design issue.

I have a backbone model that in order to update itself makes an Ajax call to the server. The result of the Ajax call is not some nice and clean json representing the model but the actual HTML that should be displayed in page.

According to the backbone conventions the view representing the model should listen for attribute changes and then render the UI representing the model.

Since the model gets directly the HTML from the server what is the suggested approach to organize my code?

My idea is to bind the view to a model attribute. When the model executes the ajax call an attribute gets updated and as a result the view gets notified (through backbone events) and fetches from the model the HTML to be displayed.

The following diagrams better explains my problem. enter image description here

Upvotes: 3

Views: 175

Answers (2)

Boti
Boti

Reputation: 3435

In your model override the parse method and store the result as an attribute. with

parse: function(response, options){
  this.set('html',response);
}

Then override the render in your view with the following:

render: function() {
    this.$el.html(this.model.get('html'));
    return this;
}

This will insert the response you got from the server into the DOM.

Upvotes: 0

Peter Lyons
Peter Lyons

Reputation: 145994

Given your API sends HTML, and treating that as a non-changeable external constraint, your proposal is pragmatic, so that's what I would do.

Upvotes: 1

Related Questions