Search code examples
javascriptjquerybackbone.jsbackbone-views

How to partially update the DOM using jQuery


My HTML is as follows:

<div id="spotPrices">
    <label class="spotLabel">Oil (WTI) $/bbl:</label>
    <INPUT type="text" id="OilSpotPrice" Size=8>
</div>

and my JavaScript:

ShowSpotPrices = Backbone.Model.extend({
    defaults: {
        wti: "0.00",
    },

    url: function () {
        return 'http://localhost:4000/api/getSpotPrices';
    },

    initialize: function () {
        console.log("Initialized ShowSpotPrices Model...")
    }
});

ShowSpotPricesView = Backbone.View.extend({
   el: '#spotPrices',
   initialize: function() {
        this.listenTo(this.model, 'sync change', this.render);
        this.model.fetch();
        this.render();
   },

    render : function() {
        //this.$("#OilSpotPrice").html("27.45");
        this.$("#OilSpotPrice").html(this.model.get('wti'));
        return this;
    }
});

var spotPrices = new ShowSpotPrices();
spotPrices.fetch({
    success: function (model) {
        console.log("New spotPrices model fetch: " + model.get('wti'));
    },
    failure: function (model) {
        console.log("Failed to fetch spotPrices model");
    }
});

var spotPricesView = new ShowSpotPricesView({model: spotPrices});
console.log("After spotPricesView.render: " + spotPricesView.model.get('wti'));

I am able to successfully fetch the wti value using the API endpoint.

However, I am unable to update #OilSpotPrice using jQuery. I have tried both updating with a fixed string value and also using model.get().


Solution

  • Set the value of the #OilSpotPrice input using the .val() jQuery function, not its inner HTML.

    this.$("#OilSpotPrice").val(this.model.get('wti'));
    

    Also, you could limit to one jQuery find call in the initialize method.

    initialize: function() {
        // cache the jQuery object of the input once
        this.$oilSpotPrice = this.$("#OilSpotPrice");
    
        this.listenTo(this.model, 'sync change', this.render);
        this.model.fetch();
        this.render();
    },
    
    render : function() {
        // then use the object
        this.$oilSpotPrice.val(this.model.get('wti'));
        return this;
    }